MongoDB에 데이터 쓰기
개요
이 페이지에는 MongoDB 에 데이터를 쓰기 (write) 데 사용할 수 있는 Java Reactive Streams 운전자 메서드의 복사 가능한 코드 예제가 포함되어 있습니다.
팁
이 페이지에 표시된 메서드에 대해 자세히 알아보려면 각 섹션에 제공된 링크를 참조하세요.
이 페이지의 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사합니다. 코드 예제의 모든 자리 표시자(예: <connection string>
)를 MongoDB 배포에 필요한 관련 값으로 바꿔야 합니다.
이 가이드 Project Reactor 라이브러리를 사용하여 Java Reactive Streams 운전자 메서드에서 반환된 Publisher
인스턴스를 사용합니다. 프로젝트 Reactor 라이브러리와 사용 방법에 대해 자세히 학습 Reactor 문서에서 시작하기 를 참조하세요.
Publisher
인스턴스를 사용하는 다른 방법도 있습니다. RxJava 와 같은 많은 대체 라이브러리 중 하나를 사용할 Publisher.subscribe()
수 Subscriber
있습니다. 또는 를 직접 호출하여 의 구현 을 전달할 수 있습니다.
이 가이드 에서는 Reactor의 Mono.block()
메서드를 사용하여 Publisher
를 구독 하고 Publisher
가 종료 상태 에 도달할 때까지 현재 스레드를 차단 합니다. Reactive Streams 이니셔티브에 학습 보려면 Reactive Streams를 참조하세요.
중요
반환된 게시자는 콜드
Java Reactive Streams 운전자 메서드가 반환하는 모든 Publisher
인스턴스는 콜드 인스턴스이므로 반환된 Publisher
을(를) 구독 하지 않는 한 해당 작업이 발생하지 않습니다. 반환된 Publisher
를 한 번만 구독 하는 것이 좋습니다. 두 번 이상 구독 하면 오류가 발생할 수 있기 때문입니다.
다음 샘플 애플리케이션을 사용하여 이 페이지의 코드 예제를 테스트할 수 있습니다. 샘플 애플리케이션을 사용하려면 다음 단계를 수행하세요.
IDE에서 새 Java 프로젝트 를 만듭니다.
Java 프로젝트 에 Java Reactive Streams 운전자 를 설치합니다.
프로젝트 리액터 라이브러리 설치 Java 프로젝트 에서 .
다음 코드를 복사하여
WriteOperations.java
이라는 새 Java 파일 에 붙여넣습니다.이 페이지에서 코드 예제를 복사하여 파일의 지정된 줄에 붙여넣습니다.
1 import com.mongodb.MongoException; 2 import com.mongodb.ConnectionString; 3 import com.mongodb.MongoClientSettings; 4 import com.mongodb.ServerApi; 5 import com.mongodb.ServerApiVersion; 6 import com.mongodb.bulk.BulkWriteResult; 7 8 import com.mongodb.client.model.DeleteOneModel; 9 import com.mongodb.client.model.InsertOneModel; 10 import com.mongodb.client.model.ReplaceOneModel; 11 import com.mongodb.client.model.UpdateOneModel; 12 import com.mongodb.client.model.DeleteOptions; 13 import com.mongodb.client.model.InsertManyOptions; 14 import com.mongodb.client.model.InsertOneOptions; 15 import com.mongodb.client.model.UpdateOptions; 16 import com.mongodb.client.model.Updates; 17 import com.mongodb.client.result.UpdateResult; 18 import com.mongodb.client.result.DeleteResult; 19 import com.mongodb.client.result.InsertManyResult; 20 import com.mongodb.client.result.InsertOneResult; 21 import com.mongodb.reactivestreams.client.MongoCollection; 22 23 import org.bson.Document; 24 25 import com.mongodb.reactivestreams.client.MongoClient; 26 import com.mongodb.reactivestreams.client.MongoClients; 27 import com.mongodb.reactivestreams.client.MongoDatabase; 28 import reactor.core.publisher.Mono; 29 30 import java.util.ArrayList; 31 import java.util.Arrays; 32 import java.util.List; 33 34 import static com.mongodb.client.model.Filters.eq; 35 import static com.mongodb.client.model.Updates.set; 36 37 class WriteOperations { 38 public static void main(String[] args) throws InterruptedException { 39 // Replace the placeholder with your Atlas connection string 40 String uri = "<connection string>"; 41 42 // Construct a ServerApi instance using the ServerApi.builder() method 43 ServerApi serverApi = ServerApi.builder() 44 .version(ServerApiVersion.V1) 45 .build(); 46 47 MongoClientSettings settings = MongoClientSettings.builder() 48 .applyConnectionString(new ConnectionString(uri)) 49 .serverApi(serverApi) 50 .build(); 51 52 // Create a new client and connect to the server 53 try (MongoClient mongoClient = MongoClients.create(settings)) { 54 MongoDatabase database = mongoClient.getDatabase("<database name>"); 55 MongoCollection<Document> collection = database.getCollection("<collection name>"); 56 // Start example code here 57 58 // End example code here 59 } 60 } 61 }
insertOne
Document document = new Document("<field name>", "<value>"); Publisher<InsertOneResult> insertOnePublisher = collection.insertOne(document); InsertOneResult result = Mono.from(insertOnePublisher).block(); System.out.printf("Inserted 1 document with ID %s.", result.getInsertedId());
insertOne()
메서드에 학습 보려면 문서 삽입 가이드 를 참조하세요.
여러 항목 삽입
Document doc1 = new Document("<field name>", "<value>"); Document doc2 = new Document("<field name>", "<value>"); List<Document> documents = Arrays.asList(doc1, doc2); Publisher<InsertManyResult> insertManyPublisher = collection.insertMany(documents); InsertManyResult result = Mono.from(insertManyPublisher).block(); System.out.printf("Inserted documents with IDs %s.", result.getInsertedIds());
insertMany()
메서드에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.
UpdateOne
Publisher<UpdateResult> updateOnePublisher = collection.updateOne( eq("<field name>", "<value>"), set("<field name>", "<new value>")); UpdateResult result = Mono.from(updateOnePublisher).block(); System.out.printf("Updated %s document.", result.getModifiedCount());
updateOne()
메서드에 대해 자세히 알아보려면 문서 업데이트 가이드를 참조하세요.
다중 업데이트
Publisher<UpdateResult> updateManyPublisher = collection.updateMany( eq("<field name>", "<value>"), set("<field name>", "<new value>")); UpdateResult result = Mono.from(updateManyPublisher).block(); System.out.printf("Updated %s documents.", result.getModifiedCount());
updateMany()
메서드에 대해 자세히 알아보려면 문서 업데이트 가이드를 참조하세요.
replaceOne
Publisher<UpdateResult> replaceOnePublisher = collection.replaceOne( eq("<field name>", "<value>"), new Document().append("<field name>", "<new value>") .append("<new field name>", "<new value>")); UpdateResult result = Mono.from(replaceOnePublisher).block(); System.out.printf("Replaced %s document.", result.getModifiedCount());
replaceOne()
메서드에 대해 자세히 알아보려면 문서 교체 가이드를 참조하세요.
deleteOne
Publisher<DeleteResult> deleteOnePublisher = collection.deleteOne( eq("<field name>", "<value>")); DeleteResult result = Mono.from(deleteOnePublisher).block(); System.out.printf("Deleted %s document.", result.getDeletedCount());
deleteOne()
메서드에 대해 자세히 알아보려면 문서 삭제 가이드를 참조하세요.
여러 항목 삭제
Publisher<DeleteResult> deleteManyPublisher = collection.deleteMany( eq("<field name>", "<value>")); DeleteResult result = Mono.from(deleteManyPublisher).block(); System.out.printf("Deleted %s documents.", result.getDeletedCount());
deleteMany()
메서드에 대해 자세히 알아보려면 문서 삭제 가이드를 참조하세요.
대량 쓰기
Publisher<BulkWriteResult> bulkWritePublisher = collection.bulkWrite( Arrays.asList(new InsertOneModel<>( new Document("<field name>", "<value>")), new InsertOneModel<>(new Document("<field name>", "<value>")), new UpdateOneModel<>(eq("<field name>", "<value>"), set("<field name>", "<new value>")), new DeleteOneModel<>(eq("<field name>", "<value>")), new ReplaceOneModel<>(eq("<field name>", "<value>"), new Document("<field name>", "<new value>") .append("<new field name>", "<new value>")))); BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block(); System.out.printf("Modified %s documents and deleted %s documents.", bulkResult.getModifiedCount(), bulkResult.getDeletedCount());