문서 메뉴
문서 홈
/ / /
Java 동기화
/ / /

삽입 작업

이 페이지의 내용

  • 개요
  • 참고 사항 _id
  • 단일 문서 삽입
  • 여러 문서를 삽입합니다.
  • 요약

이 가이드에서는 MongoDB Java 드라이버를 사용하여 문서를 삽입하는 방법을 배울 수 있습니다.

MongoDB를 사용하여 정보를 검색, 업데이트 및 삭제할 수 있습니다. 이러한 작업을 수행하려면 사용자 프로필 및 주문 등의 해당 정보가 MongoDB에 있어야 합니다. 해당 정보가 존재하려면 먼저 삽입 작업을 수행해야 합니다.

삽입 작업은 insertOne(), insertMany()bulkWrite() 메서드를 사용하여 단일 또는 여러 문서를 MongoDB에 삽입합니다.

다음 섹션에서는 insertOne()insertMany() 에 중점을 둡니다. bulkWrite() 메서드 사용 방법에 대한 자세한 내용은 대량 작업에대한 가이드를 참조하세요.

문서를 삽입할 때 MongoDB는 기본적으로 문서에 한 가지 제약 조건을 적용합니다: 각 문서에는 고유한 _id 필드가 포함 되어야 합니다.

이 필드를 관리하는 방법에는 두 가지가 있습니다:

  • 각 값이 고유하게 유지되도록 해당 필드를 직접 관리할 수 있습니다.

  • 드라이버가 고유한 ObjectId 값을 자동으로 생성하도록 할 수 있습니다.

고유성에 대한 강력한 보장을 제공하지 않는 한, 드라이버가 자동으로 _id 값을 생성하도록 하는 것이 좋습니다.

참고

중복된 _id 값은 고유 인덱스 제약 조건을 위반하여 WriteError가 발생합니다.

고유 인덱스에 대한 자세한 내용은 고유 인덱스에 대한 수동 항목을 참조하세요.

단일 문서를 삽입하려면 insertOne() 메서드를 사용합니다.

삽입이 성공하면 메서드는 새 문서의 _id를 나타내는 InsertOneResult 인스턴스를 반환합니다.

다음 예에서는 insertOne() 메서드를 사용하여 문서를 만들고 삽입합니다.

Document doc1 = new Document("color", "red").append("qty", 5);
InsertOneResult result = collection.insertOne(doc1);
System.out.println("Inserted a document with the following id: "
+ result.getInsertedId().asObjectId().getValue());

결과물은 다음과 같이 표시되어야 합니다:

Inserted a document with the following id: 60930c39a982931c20ef6cd6

이 섹션에 언급된 메서드 및 클래스에 대한 자세한 내용은 다음 API 리소스를 참조하세요.

여러 문서를 삽입하려는 경우 insertMany() 메서드를 사용합니다. 이 메소드는 예외가 발생할 때까지 지정된 순서대로 문서를 삽입합니다.

예를 들어, 다음 문서를 삽입한다고 가정합니다.

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }
{ "_id": 3, "color": "yellow", "qty": 3 }
{ "_id": 6, "color": "blue", "qty": 8 }

해당 문서를 삽입하려고 하던 중 세 번째 문서에 WriteError 오류가 발생할 경우, 오류가 발생하기 전의 문서는 이미 컬렉션에 삽입된 상태가 됩니다.

try-catch 차단을 사용하면 오류가 발생하기 전에 성공적으로 처리된 문서에 대한 승인을 받을 수 있습니다.

List<Integer> insertedIds = new ArrayList<>();
// Inserts sample documents and prints their "_id" values
try {
InsertManyResult result = collection.insertMany(documents);
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asInt32().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);
// Prints a message if any exceptions occur during the operation and the "_id" values of inserted documents
} catch(MongoBulkWriteException exception) {
exception.getWriteResult().getInserts()
.forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue()));
System.out.println("A MongoBulkWriteException occurred, but there are " +
"successfully processed documents with the following ids: " + insertedIds);
}

출력은 MongoDB가 처리할 수 있는 문서로 구성되며 다음과 같이 표시됩니다.

A MongoBulkWriteException occurred, but there are successfully processed
documents with the following ids: [3, 4, 6]

컬렉션 내부를 살펴보면 다음 문서가 표시됩니다.

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }

성공적으로 삽입되면 이 메서드는 각 새 문서의 _id 를 나타내는 InsertManyResult 인스턴스를 반환합니다.

다음 예에서는 두 개의 문서를 만들어 List 에 추가하고 insertMany() 메서드를 사용하여 List 을 삽입합니다.

List<Document> documents = new ArrayList<>();
Document doc1 = new Document("color", "red").append("qty", 5);
Document doc2 = new Document("color", "purple").append("qty", 10);
documents.add(doc1);
documents.add(doc2);
InsertManyResult result = collection.insertMany(documents);
// Retrieves and prints the ID values of each inserted document
List<ObjectId> insertedIds = new ArrayList<>();
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asObjectId().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);

결과물은 다음과 같이 표시되어야 합니다:

Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]

이 섹션에 언급된 메서드 및 클래스에 대한 자세한 내용은 다음 API 리소스를 참조하세요.

삽입 작업을 수행하는 방법에는 세 가지가 있지만 여기서는 두 가지에 중점을 두었습니다.

  • insertOne() 메서드는 단일 문서를 삽입합니다.

  • insertMany() 메서드는 여러 문서를 삽입합니다.

두 방법 모두 문서에서 필드를 생략하면 자동으로 _id 를 생성합니다.

삽입에 성공하면 두 메서드 모두 각 새 문서의 _id 를 나타내는 인스턴스를 반환합니다.

돌아가기

쓰기 작업