Docs Menu
Docs Home
/ / /
Java 동기화 드라이버
/ /

문서 삽입

MongoCollection 객체의 insertOne() 메서드를 사용하여 단일 문서를 컬렉션에 삽입할 수 있습니다. 문서를 삽입하려면 저장하려는 필드와 값이 포함된 Document 객체를 생성합니다. 아직 존재하지 않는 컬렉션에서 insertOne() 메서드를 호출하면 서버에서 자동으로 컬렉션을 생성합니다.

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

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

다음 스니펫은 movies 컬렉션에 단일 문서를 삽입합니다.

참고

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

// Inserts a sample document describing a movie by using the Java driver
package usage.examples;
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;
public class InsertOne {
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");
try {
// 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("Success! Inserted document id: " + result.getInsertedId());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to insert due to an error: " + me);
}
}
}
}

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

Inserted document id: BsonObjectId{value=...}

Legacy API

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

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

  • insertOne()

  • 문서

  • InsertOneResult

돌아가기

삽입 작업