Docs Menu
Docs Home
/ / /
Scala
/

문서 삽입

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • _id 필드
  • 문서 하나 삽입
  • 여러 문서를 삽입합니다.
  • 삽입 동작 수정
  • 예시
  • 추가 정보

이 가이드 에서는 스칼라 운전자 사용하여 삽입 작업을 수행하여 MongoDB 컬렉션 에 문서를 추가하는 방법을 학습 수 있습니다.

삽입 작업은 하나 이상의 문서를 MongoDB 컬렉션 에 삽입합니다. 다음 메서드를 사용하여 삽입 작업을 수행할 수 있습니다.

  • insertOne() 단일 문서 삽입

  • insertMany() 하나 이상의 문서를 삽입하려면

이 가이드 의 예제에서는 restaurants sample_restaurants Atlas 샘플 데이터 세트의 데이터베이스 에 있는 컬렉션 사용합니다. 스칼라 애플리케이션 에서 이 컬렉션 액세스 하려면 MongoClient Atlas cluster 에 연결하는 를 만들고 및 변수에 다음 값을 할당합니다.database collection

val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.

MongoDB 컬렉션에서 각 문서에는 고유한 필드 값이 있는 _id 필드가 포함되어야 합니다.

MongoDB를 사용하면 이 필드를 두 가지 방법으로 관리할 수 있습니다.

  • 각 문서 의 _id 필드 를 직접 설정하여 각 값이 고유하도록 합니다.

  • 운전자 가 각 문서 _id 필드 에 대해 고유한 BsonObjectId 값을 자동으로 생성하도록 합니다.

고유성을 보장할 수 없는 경우 드라이버가 _id 값을 자동으로 생성하도록 하는 것이 좋습니다.

참고

중복된 _id 값은 고유 인덱스 제약 조건을 위반하여 운전자 오류를 반환합니다.

_id 필드에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 고유 인덱스 가이드를 참조하세요.

문서 구조 및 규칙에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 가이드를 참조하세요.

MongoDB 컬렉션 에 단일 문서 추가하려면 insertOne() 메서드를 호출하고 삽입하려는 문서 전달합니다.

다음 예시에서는 restaurants 컬렉션에 문서를 삽입합니다.

val doc: Document = Document("name" -> "Neighborhood Bar & Grill", "borough" -> "Queens")
val observable: Observable[InsertOneResult] = collection.insertOne(doc)
observable.subscribe(new Observer[InsertOneResult] {
override def onNext(result: InsertOneResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=...}}
Completed

MongoDB 컬렉션 에 여러 문서를 추가하려면 insertMany() 함수를 호출하고 삽입하려는 문서 목록을 전달합니다.

다음 예시 에서는 restaurants 컬렉션 에 두 개의 문서를 삽입합니다.

val docs: Seq[Document] = Seq(
Document("name" -> "Metropolitan Cafe", "borough" -> "Queens"),
Document("name" -> "Yankee Bistro", "borough" -> "Bronx")
)
val observable: Observable[InsertManyResult] = collection.insertMany(docs)
observable.subscribe(new Observer[InsertManyResult] {
override def onNext(result: InsertManyResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}}
Completed

insertOne() 메서드는 삽입 작업을 구성하는 옵션을 설정하는 InsertOneOptions 매개 변수를 선택적으로 허용합니다. 옵션을 지정하지 않으면 운전자 는 기본값 설정으로 삽입 작업을 수행합니다. insertOne() 메서드에 마지막 매개변수로 옵션을 전달합니다.

다음 표에서는 InsertOneOptions 인스턴스 를 구성하는 데 사용할 수 있는 setter 메서드에 대해 설명합니다.

메서드
설명

bypassDocumentValidation()

If set to true, allows the driver to ignore document-level validation.
Defaults to false.

comment()

Sets a comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual for more information.

InsertManyOptions 인스턴스 구성하여 insertMany() 메서드에 대한 앞의 설정을 설정하다 수 있습니다. ordered() 세터 메서드를 사용하여 운전자 MongoDB 에 문서를 삽입하는 순서를 지정할 수도 있습니다. insertMany() 메서드에 마지막 매개변수로 옵션을 전달합니다.

다음 코드에서는 insertMany() 메서드를 사용하여 컬렉션 에 세 개의 새 문서를 삽입합니다. bypassDocumentValidation 옵션이 활성화되어 있으므로 이 삽입 작업은 문서 수준 유효성 검사 우회합니다.

val docs: Seq[Document] = Seq(
Document("name" -> "One Night's Delight", "borough" -> "Queens"),
Document("name" -> "Second Street Pub", "borough" -> "Manhattan"),
Document("name" -> "Triple Crown Diner", "borough" -> "Brooklyn")
)
val opts: InsertManyOptions = InsertManyOptions().bypassDocumentValidation(true)
val observable: Observable[InsertManyResult] = collection.insertMany(docs, opts)
observable.subscribe(new Observer[InsertManyResult] {
override def onNext(result: InsertManyResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}, 2=BsonObjectId{value=...}}}
Completed

이 가이드에서 설명하는 메서드에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

데이터 쓰기