AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

삽입 작업

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

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

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

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

참고

삽입 작업의 id_ 필드

문서 삽입할 때 MongoDB 기본값 으로 문서에 한 가지 제약 조건을 적용합니다: 각 문서 고유한 _id 값이 포함되어야 합니다. 중복된 _id 값은 고유 인덱스 제약 조건을 위반하여 WriteError(이)가 발생합니다.

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

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

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

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

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

단일 문서를 삽입하려면 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" valuestry { 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 processeddocuments 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 documentList<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]

참고

설정 예시

이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시에서는 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기에 따라 MongoDB Atlas의 무료 클러스터에서 데이터베이스에 로드할 수 있습니다.

다음 코드는 1개 삽입 작업과 다수 삽입 작업을 수행하는 완전한 독립형 파일 입니다.

// Inserts a sample document describing a movie by using the Java driver package org.example; import java.util.Arrays; import org.bson.Document;import org.bson.types.ObjectId; import com.mongodb.MongoException;import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;import com.mongodb.client.result.InsertOneResult;import com.mongodb.client.result.InsertManyResult; import java.util.List; public class Insert { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // Inserts a sample document describing a movie into the collection InsertOneResult result = collection.insertOne(new Document() .append("_id", new ObjectId()) .append("title", "Ski Bloopers") .append("genres", Arrays.asList("Documentary", "Comedy"))); // Prints the ID of the inserted document System.out.println("Inserted document id - insert one: " + result.getInsertedId()); // Creates two sample documents containing a "title" field List<Document> movieList = Arrays.asList( new Document().append("title", "Short Circuit 3"), new Document().append("title", "The Lego Frozen Movie")); // Inserts sample documents describing movies into the collection InsertManyResult result = collection.insertMany(movieList); // Prints the IDs of the inserted documents System.out.println("Inserted document id - insert many: " + result.getInsertedIds()); } }}

운전자 단일 쓰기 (write) 작업을 수행할 때 발생하는 쓰기 (write) 오류에 대해 MongoWriteException 을 발생시킵니다. MongoWriteException 객체 에는 이를 발생시킨 WriteError 객체 포함된 error 필드 있습니다.

quantity 필드 의 값이 int 유형이어야 하는 스키마 유효성 검사 규칙이 있는 컬렉션 가정해 보겠습니다. 다음 예시 에서는 quantity 값이 "three"인 문서 삽입하려고 하면 운전자 MongoWriteException 가 발생합니다.

Exception in thread "main" com.mongodb.MongoWriteException: Document failed validation atcom.mongodb.internal.connection.ProtocolHelper.getWriteException(ProtocolHelper.java:228)...Caused by: com.mongodb.MongoWriteException: WriteError{code=121,message='Document failed validation', details={ operator: "$jsonSchema",schemaRules: { bsonType: "int", description: "must be an integer" },offendingDocument: {"name":"Apple","quantity":"three"} } } atcom.mongodb.internal.connection.WriteResultHelper.createWriteException(WriteResultHelper.java:50)

스키마 유효성 검사 에 대해 자세히 학습 서버 수동 항목 섹션의 스키마 유효성 검사 참조하세요.

문서를 삽입하는 데 사용되는 메서드 및 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.

문제 해결 섹션에서 설명한 오류 유형에 대한 자세한 내용은 다음 API 문서를 참조하세요.