Docs Menu
Docs Home
/ / /
Java Reactive Streams 드라이버
/

대량 쓰기 작업

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 컬렉션 대량 쓰기
  • 삽입 작업
  • 업데이트 작업
  • 대체 작업
  • 삭제 작업
  • 대량 작업 수행
  • 대량 쓰기 사용자 지정
  • 클라이언트 대량 쓰기
  • 삽입 작업
  • 대체 작업
  • 대량 작업 수행
  • 대량 쓰기 사용자 지정
  • 추가 정보
  • API 문서

이 가이드 에서는 대량 쓰기 (write) 작업 을 사용하여 단일 데이터베이스 호출에서 여러 쓰기 (write) 작업을 수행하는 방법에 학습 설명합니다.

문서 삽입하고, 다른 여러 문서를 업데이트 다음, 문서 삭제 하려는 시나리오를 가정해 보겠습니다. 개별 메서드를 사용하는 경우 각 작업에는 자체 데이터베이스 호출이 필요합니다.

대량 쓰기 (write) 작업을 사용하면 더 적은 수의 데이터베이스 호출로 여러 쓰기 (write) 작업을 수행할 수 있습니다. 다음 수준에서 대량 쓰기 (write) 작업을 수행할 수 있습니다.

  • 컬렉션:MongoCollection.bulkWrite() 메서드를 사용하여 단일 컬렉션 에 대해 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드에서는 각 종류의 쓰기 (write) 작업에 하나 이상의 데이터베이스 호출이 필요합니다. 예시 를 들어 는MongoCollection.bulkWrite() 여러 업데이트 작업을 한 번의 호출에 처리하지만 삽입 작업과 바꾸기 작업에 대해 데이터베이스 두 번 개별적으로 호출합니다.

  • 클라이언트: 애플리케이션 MongoDB Server 버전 이상에 연결되는 8.0 경우 메서드를 사용하여 MongoClient.bulkWrite() 동일한 클러스터 의 여러 컬렉션 및 데이터베이스에서 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드는 한 번의 데이터베이스 호출로 모든 쓰기 (write) 작업을 수행합니다.

이 가이드 의 예제에서는 sample_restaurants.restaurants Atlas 샘플 데이터 세트의 컬렉션 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 시작하기 튜토리얼을 참조하세요.

중요

프로젝트 리액터 라이브러리

이 가이드 Project Reactor 라이브러리를 사용하여 Java Reactive Streams 운전자 메서드에서 반환된 Publisher 인스턴스를 사용합니다. 프로젝트 Reactor 라이브러리와 사용 방법에 대해 자세히 학습 Reactor 문서에서 시작하기 를 참조하세요. 이 가이드 에서 Project Reactor 라이브러리 메서드를 사용하는 방법에 대해 자세히 학습 MongoDB 에 데이터 쓰기 가이드 참조하세요.

대량 쓰기 (write) 작업에는 하나 이상의 쓰기 (write) 작업이 포함됩니다. 컬렉션 수준에서 대량 쓰기 (write) 작업을 수행하려면 WriteModel 문서의 ListMongoCollection.bulkWrite() 메서드에 전달합니다. WriteModel 는 쓰기 (write) 작업을 나타내는 모델입니다.

수행하려는 각 쓰기 (write) 작업에 대해 WriteModel에서 상속되는 다음 클래스 중 하나의 인스턴스 만듭니다.

  • InsertOneModel

  • UpdateOneModel

  • UpdateManyModel

  • ReplaceOneModel

  • DeleteOneModel

  • DeleteManyModel

다음 섹션에서는 이전 클래스의 인스턴스를 만들고 사용하는 방법을 보여줍니다.

삽입 작업을 수행하려면 InsertOneModel 인스턴스 를 만들고 삽입하려는 문서 를 전달합니다.

다음 예에서는 InsertOneModel 인스턴스를 만듭니다.

InsertOneModel<Document> operation = new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches"));

여러 문서를 삽입하려면 각 문서 에 대해 InsertOneModel 인스턴스 를 만듭니다.

문서를 업데이트하려면 UpdateOneModel 인스턴스를 만들고 다음 인수를 전달합니다.

  • 컬렉션 의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터하다 입니다.

  • 수행하려는 업데이트 작업 입니다. 업데이트 작업에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 를 참조하세요.

다음 예에서는 UpdateOneModel 인스턴스를 만듭니다.

UpdateOneModel<Document> operation = new UpdateOneModel<>(
eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads"));

여러 문서가 UpdateOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 업데이트합니다. 다음 코드와 같이 UpdateOptions 인스턴스 에서 정렬을 지정하여 운전자 업데이트 작업을 수행하기 전에 일치하는 문서에 순서를 적용 수 있습니다.

UpdateOptions options = UpdateOptions.sort(Sorts.ascending("_id"));

여러 문서를 업데이트 하려면 UpdateManyModel 인스턴스 를 만들고 동일한 인수를 전달합니다. UpdateManyModel 은 쿼리 필터하다 와 일치하는 모든 문서를 업데이트합니다.

다음 예에서는 UpdateManyModel 인스턴스를 만듭니다.

UpdateManyModel<Document> operation = new UpdateManyModel<>(
eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads"));

바꾸기 작업은 _id 필드 를 제외하고 지정된 문서 의 모든 필드와 값을 제거하고 새 항목으로 바꿉니다. 바꾸기 작업을 수행하려면 ReplaceOneModel 인스턴스 를 만들고 쿼리 필터하다 와 일치하는 문서 에 저장 하려는 필드 및 값을 전달합니다.

다음 예에서는 ReplaceOneModel 인스턴스를 만듭니다.

ReplaceOneModel<Document> operation = new ReplaceOneModel<>(
eq("name", "Original Pizza"),
new Document("name", "Mongo's Pizza")
.append("borough", "Manhattan"));

여러 문서가 ReplaceOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 대체합니다. 다음 코드와 같이 ReplaceOptions 인스턴스 에서 정렬을 지정하여 운전자 바꾸기 작업을 수행하기 전에 일치하는 문서에 순서를 적용 할 수 있습니다.

ReplaceOptions options = ReplaceOptions.sort(Sorts.ascending("_id"));

여러 문서 바꾸기

여러 문서를 바꾸려면 각 문서 에 대해 ReplaceOneModel 인스턴스 를 만듭니다.

문서 를 삭제 하려면 DeleteOneModel 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. DeleteOneModel 은 쿼리 필터하다 와 일치 하는 첫 번째 문서 만 제거합니다.

다음 예에서는 DeleteOneModel 인스턴스를 만듭니다.

DeleteOneModel<Document> operation = new DeleteOneModel<>(
eq("restaurant_id", "5678"));

여러 문서를 삭제 하려면 DeleteManyModel 인스턴스 를 만들고 삭제 하려는 문서를 지정하는 쿼리 필터하다 를 전달합니다. DeleteManyModel 은 쿼리 필터하다 와 일치하는 모든 문서를 제거합니다.

다음 예에서는 DeleteManyModel 인스턴스를 만듭니다.

DeleteManyModel<Document> operation = new DeleteManyModel<>(
eq("name", "Mongo's Deli"));

수행하려는 각 작업에 대해 WriteModel 인스턴스 정의한 후 이러한 인스턴스 목록을 bulkWrite() 메서드에 전달합니다. 기본값 으로 이 메서드는 목록에 정의된 순서대로 작업을 실행합니다.

다음 예시 에서는 bulkWrite() 메서드를 사용하여 여러 쓰기 (write) 작업을 수행합니다.

Publisher<BulkWriteResult> bulkWritePublisher = restaurants.bulkWrite(
Arrays.asList(new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Manhattan")
.append("restaurant_id", "1234")),
new InsertOneModel<>(new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Brooklyn")
.append("restaurant_id", "5678")),
new UpdateManyModel<>(eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads")),
new DeleteOneModel<>(eq("restaurant_id", "1234"))));
BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block();
System.out.println(bulkResult.toString());
AcknowledgedBulkWriteResult{insertedCount=2, matchedCount=2, removedCount=1, modifiedCount=2, upserts=[], inserts=[BulkWriteInsert{index=0, id=BsonObjectId{value=66a7e0a6c08025218b657208}}, BulkWriteInsert{index=1, id=BsonObjectId{value=66a7e0a6c08025218b657209}}]}

쓰기 (write) 작업 중 하나라도 실패하면 Java Reactive Streams 운전자 는 MongoBulkWriteException 신호를 보내고 더 이상 개별 작업을 수행하지 않습니다. MongoBulkWriteException 에는 개별 장애에 대한 세부 정보를 제공하는 MongoBulkWriteException.getWriteErrors() 메서드를 사용하여 액세스할 수 있는 BulkWriteError 가 포함되어 있습니다.

참고

Java Reactive Streams 운전자 가 대량 작업을 실행할 때 작업이 실행 컬렉션 의 writeConcern 을(를) 사용합니다. 운전자 는 실행 순서에 관계없이 모든 작업을 시도한 후 모든 쓰기 고려 (write concern) 오류를 보고합니다.

BulkWriteOptions 클래스에는 bulkWrite() 메서드의 동작을 수정하는 메서드가 포함되어 있습니다. BulkWriteOptions 클래스를 사용하려면 클래스의 새 인스턴스 를 구성한 다음 해당 메서드 중 하나 이상을 호출하여 쓰기 (write) 작업을 수정합니다. 이러한 메서드 호출을 함께 연결할 수 있습니다. 쓰기 (write) 작업의 동작을 수정하려면 클래스 인스턴스 를 bulkWrite() 메서드의 마지막 인수로 전달합니다.

BulkWriteOptions 클래스에서 다음 메서드를 사용하여 쓰기 (write) 메서드를 수정할 수 있습니다. 모든 메서드는 선택 사항입니다.

메서드
설명

bypassDocumentValidation(Boolean bypassDocumentValidation)

Specifies whether the bulk write operation bypasses document validation. This lets you perform write operations on documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.

comment(Bson comment)

Attaches a Bson comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

comment(String comment)

Attaches a String comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

let(Bson variables)

Specifies a map of parameter names and values. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.

ordered(Boolean ordered)

If set to True, the driver performs the individual operations in the order provided. If an individual operation fails, the driver will not execute any subsequent individual operations.
Defaults to True.

다음 예시 에서는 앞의 예시 에서 bulkWrite() 메서드를 호출하지만 ordered 옵션을 False 로 설정합니다.

Publisher<BulkWriteResult> bulkWritePublisher = restaurants.bulkWrite(
Arrays.asList(new InsertOneModel<>(
new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Manhattan")
.append("restaurant_id", "1234")),
new InsertOneModel<>(new Document("name", "Mongo's Deli")
.append("cuisine", "Sandwiches")
.append("borough", "Brooklyn")
.append("restaurant_id", "5678")),
new UpdateManyModel<>(eq("name", "Mongo's Deli"),
set("cuisine", "Sandwiches and Salads")),
new DeleteOneModel<>(eq("restaurant_id", "1234"))),
new BulkWriteOptions().ordered(false));
BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block();
System.out.println(bulkResult.toString());
AcknowledgedBulkWriteResult{insertedCount=2, matchedCount=2, removedCount=1, modifiedCount=2, upserts=[], inserts=[BulkWriteInsert{index=0, id=BsonObjectId{value=66a7e03cce430c5854b6caf9}}, BulkWriteInsert{index=1, id=BsonObjectId{value=66a7e03cce430c5854b6cafa}}]}

순서가 지정되지 않은 대량 쓰기 (write) 의 쓰기 (write) 작업 중 하나라도 실패하면 Java Reactive Streams 운전자 는 모든 작업을 시도한 후에만 오류를 보고합니다.

참고

순서가 지정되지 않은 대량 작업은 실행 순서가 보장되지 않습니다. 이 순서는 런타임을 최적화하기 위해 나열한 방식과 다를 수 있습니다.

MongoDB Server 8.0 이상을 실행 배포서버 에 연결할 때 MongoClient.bulkWrite() 메서드를 사용하여 동일한 클러스터 의 여러 데이터베이스 및 컬렉션에 쓰기 (write) 수 있습니다. MongoClient.bulkWrite() 메서드는 한 번의 호출로 모든 쓰기 (write) 작업을 수행합니다.

MongoClient.bulkWrite() 메서드는 ClientNamespacedWriteModel 인스턴스 목록을 사용하여 다양한 쓰기 (write) 작업을 나타냅니다. 인스턴스 메서드를 사용하여 ClientNamespacedWriteModel 인터페이스의 인스턴스를 구성할 수 있습니다. 예시 를 들어 ClientNamespacedInsertOneModel 의 인스턴스 하나의 문서 삽입하는 작업을 나타내며 ClientNamespacedWriteModel.insertOne() 메서드를 사용하여 이 모델을 만들 수 있습니다.

모델과 해당 인스턴스 메서드는 아래 표에 설명되어 있습니다.

모델
인스턴스 메서드
설명
매개변수

ClientNamespacedInsertOneModel

insertOne()

namespace에 문서 삽입할 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

document: 삽입할 문서

ClientNamespacedUpdateOneModel

updateOne()

filter와 일치하는 namespace 의 첫 번째 문서 업데이트 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 업데이트 할 문서 선택하는 필터

update: 일치하는 문서 에 적용 업데이트

updatePipeline: 일치하는 문서 에 적용 파이프라인 업데이트

options: (선택 사항) 문서 업데이트 시 적용 옵션

update 또는 updatePipeline 매개변수 값을 전달해야 합니다.

ClientNamespacedUpdateManyModel

updateMany()

filter와 일치하는 namespace 의 모든 문서를 업데이트 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 업데이트 할 문서를 선택하는 필터

update: 일치하는 문서에 적용 업데이트

updatePipeline: 일치하는 문서에 적용 파이프라인 업데이트

options: (선택 사항) 문서 업데이트 시 적용 옵션

update 또는 updatePipeline 매개변수 값을 전달해야 합니다.

ClientNamespacedReplaceOneModel

replaceOne()

filter와 일치하는 namespace 의 첫 번째 문서 대체할 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 대체할 문서 선택하는 필터

replacement: 대체 문서

options: (선택 사항) 문서를 교체할 때 적용 옵션

ClientNamespacedDeleteOneModel

deleteOne()

namespace 에서 filter과 일치하는 첫 번째 문서 삭제 하는 모델을 생성합니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 삭제 문서 선택하는 필터

option: (선택 사항) 문서 삭제할 때 적용 할 옵션

ClientNamespacedDeleteManyModel

deleteMany()

filter와(과) 일치하는 namespace 의 모든 문서를 삭제 하는 모델을 생성합니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 삭제 문서를 선택하는 필터

option: (선택 사항) 문서를 삭제할 때 적용 할 옵션

다음 섹션에서는 모델을 만들고 클라이언트 bulkWrite() 메서드를 사용하는 방법에 대한 몇 가지 예를 제공합니다.

이 예시 두 개의 문서를 삽입하기 위한 지침이 포함된 모델을 만드는 방법을 보여 줍니다. 한 문서 db.people 컬렉션 에 삽입되고 다른 문서 db.things 컬렉션 에 삽입됩니다. MongoNamespace 인스턴스 각 쓰기 (write) 작업이 적용되는 대상 데이터베이스 및 컬렉션 정의합니다.

ClientNamespacedInsertOneModel personToInsert = ClientNamespacedWriteModel
.insertOne(
new MongoNamespace("db", "people"),
new Document("name", "Julia Smith")
);
ClientNamespacedInsertOneModel thingToInsert = ClientNamespacedWriteModel
.insertOne(
new MongoNamespace("db", "things"),
new Document("object", "washing machine")
);

다음 예시 db.peopledb.things 컬렉션의 기존 문서를 대체하는 모델을 만드는 방법을 보여 줍니다.

ClientNamespacedReplaceOneModel personReplacement = ClientNamespacedWriteModel
.replaceOne(
new MongoNamespace("db", "people"),
Filters.eq("_id", 1),
new Document("name", "Frederic Hilbert")
);
ClientNamespacedReplaceOneModel thingReplacement = ClientNamespacedWriteModel
.replaceOne(
new MongoNamespace("db", "things"),
Filters.eq("_id", 1),
new Document("object", "potato")
);

이 예시 성공적으로 실행되면 people 컬렉션 에서 _id 값이 1 인 문서 새 문서 로 대체됩니다. things 컬렉션 의 _id 값이 1 인 문서 새 문서 로 대체됩니다.

수행하려는 각 작업에 대해 ClientNamespacedWriteModel 인스턴스 정의한 후 이러한 인스턴스 목록을 클라이언트 bulkWrite() 메서드에 전달합니다. 기본값 으로 이 메서드는 지정된 순서대로 작업을 실행합니다.

다음 예시 에서는 bulkWrite() 메서드를 사용하여 여러 쓰기 (write) 작업을 수행합니다.

MongoNamespace peopleNamespace = new MongoNamespace("db", "people");
MongoNamespace thingsNamespace = new MongoNamespace("db", "things");
List<ClientNamespacedWriteModel> bulkOperations = Arrays.asList(
ClientNamespacedWriteModel
.insertOne(
peopleNamespace,
new Document("name", "Corey Kopper")
),
ClientNamespacedWriteModel
.replaceOne(
thingsNamespace,
Filters.eq("_id", 1),
new Document("object", "potato")
)
);
Publisher<ClientBulkWriteResult> bulkWritePublisher = mongoClient
.bulkWrite(bulkOperations);
ClientBulkWriteResult clientBulkResult = Mono
.from(bulkWritePublisher)
.block();
System.out.println(clientBulkResult.toString());
AcknowledgedSummaryClientBulkWriteResult{insertedCount=1, matchedCount=1, ...}

쓰기 (write) 작업 중 하나라도 실패하면 운전자 ClientBulkWriteException 를 발생시키고 더 이상 개별 작업을 수행하지 않습니다. ClientBulkWriteException 에는 개별 장애에 대한 세부 정보를 제공하는 ClientBulkWriteException.getWriteErrors() 메서드를 사용하여 액세스할 수 있는 BulkWriteError 가 포함되어 있습니다.

ClientBulkWriteOptions 인스턴스 bulkWrite() 메서드에 전달하여 운전자 대량 쓰기 (write) 작업을 수행하는 방식을 사용자 지정할 수 있습니다.

기본값 으로 운전자 오류가 발생하거나 작업이 성공적으로 완료될 때까지 지정한 순서대로 개별 작업을 대량 작업으로 실행합니다.

그러나 ClientBulkWriteOptions 인스턴스 만들 때 falseordered() 메서드에 전달하여 운전자 순서가 지정되지 않은 방식으로 쓰기 (write) 작업을 수행하도록 지시할 수 있습니다. 순서가 지정되지 않은 옵션을 사용할 때 오류가 발생하는 작업은 운전자 대량 쓰기 (write) 작업에서 다른 쓰기 (write) 작업을 실행 것을 막지 않습니다.

다음 코드는 ClientBulkWriteOptions 인스턴스 에서 ordered 옵션을 false 로 설정하고 대량 쓰기 (write) 작업을 수행하여 여러 문서를 삽입합니다.

MongoNamespace namespace = new MongoNamespace("db", "people");
ClientBulkWriteOptions options = ClientBulkWriteOptions
.clientBulkWriteOptions()
.ordered(false);
List<ClientNamespacedWriteModel> bulkOperations = Arrays.asList(
ClientNamespacedWriteModel.insertOne(
namespace,
new Document("_id", 1).append("name", "Rudra Suraj")
),
// Causes a duplicate key error
ClientNamespacedWriteModel.insertOne(
namespace,
new Document("_id", 1).append("name", "Mario Bianchi")
),
ClientNamespacedWriteModel.insertOne(
namespace,
new Document("name", "Wendy Zhang")
)
);
Publisher<ClientBulkWriteResult> bulkWritePublisher = mongoClient
.bulkWrite(bulkOperations, options);

중복 키가 있는 문서 삽입하는 쓰기 (write) 작업으로 인해 오류가 발생하더라도 쓰기 (write) 작업이 순서가 지정되지 않았으므로 다른 작업은 수행됩니다.

개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

삭제