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

여러 문서를 삽입합니다.

MongoCollection 객체에서 insertMany() 메서드를 호출하여 한 번의 작업으로 collection에 여러 문서를 삽입할 수 있습니다. 삽입하려면 Document 객체를 List 에 추가하고 해당 ListinsertMany() 에 인수로 전달합니다. 아직 존재하지 않는 collection에서 insertMany() 메서드를 호출하면 서버에서 collection을 생성합니다.

삽입에 성공하면 insertMany()InsertManyResult 인스턴스를 반환합니다. InsertManyResult 인스턴스에서 getInsertedIds() 메서드를 호출하여 삽입한 문서의 _id 필드와 같은 정보를 검색할 수 있습니다.

삽입 작업이 실패하면 드라이버에서 예외가 발생합니다. 특정 조건에서 발생하는 예외 유형에 대한 자세한 내용은 이 페이지 하단에 링크된 insertMany() 에 대한 API 문서를 참조하세요.

다음 스니펫은 movies collection에 여러 문서를 삽입합니다.

참고

이 예제에서는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

package usage.examples;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
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.InsertManyResult;
public class InsertMany {
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");
List<Document> movieList = Arrays.asList(
new Document().append("title", "Short Circuit 3"),
new Document().append("title", "The Lego Frozen Movie"));
try {
InsertManyResult result = collection.insertMany(movieList);
System.out.println("Inserted document ids: " + result.getInsertedIds());
} catch (MongoException me) {
System.err.println("Unable to insert due to an error: " + me);
}
}
}
}

예시를 실행하면 다음과 같이 값 필드에 삽입된 문서의 ObjectId 값과 함께 다음과 유사한 출력이 표시됩니다.

Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}

레거시 API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 API 설명서를 참조하세요.

  • insertMany()

  • 문서

  • InsertManyResult

돌아가기

문서 삽입