개요
이 가이드 에서는 대량 쓰기 (write) 작업 을 사용하여 단일 데이터베이스 호출에서 여러 쓰기 (write) 작업을 수행하는 방법에 학습 설명합니다.
문서 삽입하고, 다른 여러 문서를 업데이트 다음, 문서 삭제 하려는 시나리오를 가정해 보겠습니다. 개별 메서드를 사용하는 경우 각 작업에는 자체 데이터베이스 호출이 필요합니다.
대량 쓰기 (write) 작업을 사용하면 더 적은 수의 데이터베이스 호출로 여러 쓰기 (write) 작업을 수행할 수 있습니다. 다음 수준에서 대량 쓰기 (write) 작업을 수행할 수 있습니다.
Collection: You can use the
IMongoCollection.BulkWrite()orIMongoCollection.BulkWriteAsync()method to perform bulk write operations on a single collection. These methods make a database call for each type of write operation. For example, the methods perform multiple update operations in one call, but make two separate calls to the database for an insert operation and a replace operation.클라이언트:애플리케이션 이 MongoDB Server 버전 에 연결되는 8 경우.0 이상에서는
IMongoClient.BulkWrite()또는IMongoClient.BulkWriteAsync()메서드를 사용하여 동일한 클러스터 에 있는 여러 컬렉션 및 데이터베이스에서 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드는 한 번의 데이터베이스 호출로 모든 쓰기 (write) 작업을 수행합니다.
샘플 데이터
이 가이드의 예제에서는 Atlas 샘플 데이터 세트의 sample_restaurants.restaurants 및 sample_mflix.movies 컬렉션을 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB 시작하기 가이드를 참조하세요.
팁
POCO를 사용한 대량 쓰기 작업
이 가이드 의 예제에서는 모든 일반 클래스의 TDocument 유형에 BsonDocument 유형을 사용합니다. 이러한 클래스에 POCO(Plain Old CLR Object)를 사용할 수도 있습니다. 이렇게 하려면 컬렉션 의 문서를 나타내는 클래스를 정의해야 합니다. 클래스에는 문서의 필드와 일치하는 속성이 있어야 합니다. 자세한 내용은 POCO를 참조하세요.
컬렉션 대량 쓰기
대량 쓰기 (write) 작업에는 하나 이상의 쓰기 (write) 작업이 포함됩니다. 수행하려는 각 쓰기 (write) 작업에 대해 다음 WriteModel<TDocument> 클래스 중 하나의 인스턴스 를 만듭니다.
DeleteManyModel<TDocument>DeleteOneModel<TDocument>InsertOneModel<TDocument>ReplaceOneModel<TDocument>UpdateManyModel<TDocument>UpdateOneModel<TDocument>
The following sections show how to create and use instances of the preceding classes to perform the corresponding write operation in a bulk write operation. The Perform the Bulk Operation section demonstrates how to pass a list of models to the BulkWrite() or BulkWriteAsync() method to perform the bulk operation.
삽입 작업
삽입 작업을 수행하려면 InsertOneModel<TDocument> 인스턴스 를 만들고 삽입하려는 문서 를 지정합니다.
다음 예시 에서는 InsertOneModel<BsonDocument> 클래스의 인스턴스 를 만듭니다. 이 인스턴스 는 운전자 에 "name" 필드 가 "Mongo's Deli" 인 문서 를 restaurants 컬렉션 에 삽입하도록 지시합니다.
var insertOneModel = new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } );
여러 문서를 삽입하려면 각 문서 에 대해 InsertOneModel<TDocument> 인스턴스 를 만듭니다.
중요
중복 키 오류
대량 작업을 수행할 때 InsertOneModel<TDocument> 은 컬렉션 에 이미 존재하는 _id 이 있는 문서 를 삽입할 수 없습니다. 이 상황에서 운전자 는 MongoBulkWriteException 를 발생시킵니다.
업데이트 작업
단일 문서 업데이트 하려면 UpdateOneModel<TDocument> 인스턴스 를 만들고 다음 인수를 전달합니다.
컬렉션 의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터입니다. 쿼리 지정에 대해 자세히 학습하려면 MongoDB Server 매뉴얼의 쿼리 및 프로젝션 연산자 를 참조하세요.
Update document that describes the update to perform. To learn more about specifying an update, see Update Operators in the MongoDB Server manual.
UpdateOneModel<TDocument> 인스턴스 는 쿼리 필터하다 와 일치 하는 첫 번째 문서 에 대한 업데이트 를 지정합니다.
다음 코드 예시 에서 UpdateOneModel<BsonDocument> 객체 는 restaurants 컬렉션 에 대한 업데이트 작업을 나타냅니다. 이 작업은 name 필드 값이 "Mongo's Deli"인 컬렉션 의 첫 번째 문서 와 일치합니다. 그런 다음 일치하는 문서 의 cuisine 필드 값을 "Sandwiches and Salads"(으)로 업데이트합니다.
var updateOneModel = new UpdateOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
여러 문서를 업데이트 하려면 UpdateManyModel<TDocument> UpdateOneModel<TDocument>인스턴스 를 만들고 와 동일한 인수를 전달합니다. UpdateManyModel<TDocument> 클래스는 쿼리 필터하다 와 일치하는 모든 문서에 대한 업데이트를 지정합니다.
다음 코드 예시 에서 UpdateManyModel<BsonDocument> 객체 는 restaurants 컬렉션 에 대한 업데이트 작업을 나타냅니다. 이 작업은 name 필드 값이 "Mongo's Deli"인 컬렉션 의 모든 문서와 일치합니다. 그런 다음 cuisine 필드 의 값을 "Sandwiches and Salads"(으)로 업데이트합니다.
var updateManyModel = new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
대체 작업
바꾸기 작업은 지정된 문서 의 모든 필드와 값을 제거하고 사용자가 지정한 새 필드와 값으로 바꿉니다. 대체 작업을 수행하려면 ReplaceOneModel<TDocument> 인스턴스 를 만들고 쿼리 필터하다 와 일치하는 문서 를 대체할 필드 및 값을 전달합니다.
다음 예시 에서 ReplaceOneModel<BsonDocument> 객체 는 restaurants 컬렉션 에 대한 바꾸기 작업을 나타냅니다. 이 작업은 restaurant_id 필드 값이 "1234"인 컬렉션 의 문서 와 일치합니다. 그런 다음 이 문서 에서 _id 이외의 모든 필드를 제거하고 name, cuisine, borough 및 restaurant_id 필드에 새 값을 설정합니다.
var replaceOneModel = new ReplaceOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234"), new BsonDocument{ { "name", "Mongo's Pizza" }, { "cuisine", "Pizza" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } );
여러 문서를 바꾸려면 각 문서 에 대해 ReplaceOneModel<TDocument> 인스턴스 를 만들어야 합니다.
삭제 작업
문서 를 삭제 하려면 DeleteOneModel<TDocument> 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. DeleteOneModel<TDocument> 인스턴스 는 쿼리 필터하다 와 일치 하는 첫 번째 문서 만 삭제 하는 지침을 제공합니다.
다음 코드 예시 에서 DeleteOneModel<BsonDocument> 객체 는 restaurants 컬렉션 에 대한 삭제 작업을 나타냅니다. 이 작업은 restaurant_id 필드 값이 "5678" 인 첫 번째 문서 를 일치시키고 삭제합니다.
var deleteOneModel = new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678") );
여러 문서를 삭제 하려면 DeleteManyModel<TDocument> 인스턴스 를 만들고 삭제 하려는 문서를 지정하는 쿼리 필터하다 전달합니다. DeleteManyModel<TDocument> 인스턴스는 쿼리 필터와 일치하는 모든 문서를 제거 지침을 제공합니다.
다음 코드 예시 에서 DeleteManyModel<BsonDocument> 객체 는 restaurants 컬렉션 에 대한 삭제 작업을 나타냅니다. 이 작업은 name 필드 값이 "Mongo's Deli" 인 모든 문서를 일치시키고 삭제합니다.
var deleteManyModel = new DeleteManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli") );
대량 작업 수행
수행하려는 각 작업에 대해 WriteModel 인스턴스 정의한 후 IEnumerable 인터페이스를 구현하는 클래스의 인스턴스 만듭니다. 이 IEnumerable에 WriteModel 객체를 추가한 다음 IEnumerable 를 BulkWrite() 또는 BulkWriteAsync() 메서드에 전달합니다. 기본값 으로 이러한 메서드는 목록에 정의된 순서대로 작업을 실행 .
팁
IEnumerable
Array 및 List 은 IEnumerable 인터페이스를 구현 하는 두 가지 일반적인 클래스입니다.
동기 BulkWrite() 메서드 및 비동기 BulkWriteAsync() 메서드를 사용하여 restaurants 컬렉션 에서 대량 쓰기 (write) 작업을 수행하는 방법을 보려면 다음 탭에서 선택합니다.
var models = new List<WriteModel<BsonDocument>> { new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = collection.BulkWrite(models); Console.WriteLine(results);
var models = new List<WriteModel<BsonDocument>> { new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = await collection.BulkWriteAsync(models); Console.WriteLine(results);
앞의 코드 예제는 다음과 같은 출력을 생성합니다.
MongoDB.Driver.BulkWriteResult1+Acknowledged[MongoDB.Bson.BsonDocument]
참고
운전자 가 대량 작업을 실행할 때 대상 컬렉션 의 쓰기 고려 (write concern) 를 사용합니다. 운전자 는 실행 순서에 관계없이 모든 작업을 시도한 후 모든 쓰기 고려 (write concern) 오류를 보고합니다.
대량 쓰기 작업 사용자 지정
BulkWrite() 또는 BulkWriteAsync() 메서드를 호출할 때 BulkWriteOptions 클래스의 인스턴스 를 전달할 수 있습니다. BulkWriteOptions 클래스에는 대량 쓰기 (write) 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 다음 속성이 포함되어 있습니다.
속성 | 설명 |
|---|---|
| Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual. |
| A comment to attach to the operation, in the form of a |
|
|
| A map of parameter names and values, in the form of a |
다음 코드 예제에서는 BulkWriteOptions 객체 사용하여 순서가 지정되지 않은 대량 쓰기 (write) 작업을 수행합니다.
반환 값
BulkWrite() 및 BulkWriteAsync() 메서드는 다음 속성을 포함하는 BulkWriteResult 객체 를 반환합니다.
속성 | 설명 |
|---|---|
| 서버가 일괄 쓰기 (write) 작업을 인식했는지 여부를 나타냅니다. 이 속성의 값이 |
| 삭제된 문서 수(있는 경우). |
| 삽입된 문서 수입니다(있는 경우). |
| 적용 가능한 경우 업데이트와 일치한 문서의 수. |
| 수정된 문서 수입니다(있는 경우). |
| 수정된 카운트를 사용할 수 있는지 여부를 나타냅니다. |
| 업서트 작업이 수행된 각 요청에 대한 정보가 포함된 목록입니다. |
| 불크 작업의 요청 수. |
예외 처리
대량 쓰기 (write) 작업의 작업 중 하나라도 실패하면 .NET/ C# 드라이버 는 BulkWriteError 를 발생시키고 더 이상의 작업을 수행하지 않습니다.
BulkWriteError 객체 에는 오류를 일으킨 요청 의 인덱스 설명하는 Index 속성 포함되어 있습니다.
클라이언트 대량 쓰기
MongoDB Server 8.0 이상을 실행 배포서버 에 연결할 때 IMongoClient.BulkWrite() 또는 IMongoClient.BulkWriteAsync() 메서드를 사용하여 동일한 클러스터 의 여러 데이터베이스 및 컬렉션에 쓰기 (write) 수 있습니다. 이러한 메서드는 한 번의 호출로 모든 쓰기 (write) 작업을 수행합니다.
수행하려는 각 쓰기 (write) 작업에 대해 다음 BulkWriteModel 클래스 중 하나의 인스턴스 를 만듭니다.
BulkWriteInsertOneModel<TDocument>BulkWriteUpdateOneModel<TDocument>BulkWriteUpdateManyModel<TDocument>BulkWriteReplaceOneModel<TDocument>BulkWriteDeleteOneModel<TDocument>BulkWriteDeleteManyModel<TDocument>
The following sections show how to create and use instances of the preceding classes to perform the corresponding write operation in a bulk write. The Perform the Bulk Operation section demonstrates how to pass a list of models to the BulkWrite() or BulkWriteAsync() method to perform the bulk operation.
삽입 작업
삽입 작업을 수행하려면 BulkWriteInsertOneModel<TDocument> 클래스의 인스턴스 를 만듭니다. BulkWriteInsertOneModel<TDocument> 생성자는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| The database and collection to insert the BSON document into. |
| 컬렉션에 삽입할 문서입니다. |
다음 예시 BulkWriteInsertOneModel<TDocument> 클래스의 인스턴스를 만듭니다. 이러한 인스턴스는 운전자 에 sample_restaurants.restaurants 및 sample_mflix.movies 컬렉션에 문서를 삽입하도록 지시합니다.
var restaurantToInsert = new BulkWriteInsertOneModel<BsonDocument>( "sample_restaurants.restaurants", new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ); var movieToInsert = new BulkWriteInsertOneModel<BsonDocument>( "sample_mflix.movies", new BsonDocument{ { "title", "Silly Days" }, { "year", 2022 } } );
업데이트 작업
단일 문서 를 업데이트 하려면 BulkWriteUpdateOneModel<TDocument> 클래스의 인스턴스 를 만듭니다. BulkWriteUpdateOneModel<TDocument> 생성자는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| The database and collection to insert the BSON document into. |
| The query filter that specifies the criteria used to match documents in your collection. The |
| The update operation you want to perform. For more information about update operations, see Field Update Operators in the MongoDB Server manual. |
| |
| Optional. The index to use to scan for documents. See the MongoDB Server manual for more information. |
| Optional. Specifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information. |
| Specifies which array elements to modify for an update operation on an array field. See the MongoDB Server manual for more information. |
다음 코드 예시 에서 BulkWriteUpdateOneModel<BsonDocument> 객체는 sample_restaurants.restaurants 및 sample_mflix.movies 컬렉션에 대한 업데이트 작업을 나타냅니다.
var restaurantUpdate = new BulkWriteUpdateOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ); var movieUpdate = new BulkWriteUpdateOneModel<BsonDocument>( "sample_mflix.movies", Builders<BsonDocument>.Filter.Eq("title", "Carrie"), Builders<BsonDocument>.Update.Set("seen", True) );
여러 문서를 업데이트 하려면 BulkWriteUpdateManyModel<TDocument> 클래스의 인스턴스 를 만듭니다. 이 클래스의 생성자는 BulkWriteUpdateOneModel<TDocument> 생성자와 동일한 매개변수를 허용합니다. BulkWriteUpdateManyModel<TDocument> 작업은 쿼리 필터하다 와 일치하는 모든 문서를 업데이트합니다.
다음 코드 예시 에서 BulkWriteUpdateManyModel<BsonDocument> 객체 는 sample_restaurants.restaurants 컬렉션 에 대한 업데이트 작업을 나타냅니다. 이 작업은 name 필드 값이 "Starbucks"인 컬렉션 의 모든 문서와 일치합니다. 그런 다음 cuisine 필드 의 값을 "Coffee (Chain)"(으)로 업데이트합니다.
var updateManyModel = new BulkWriteUpdateManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Starbucks"), Builders<BsonDocument>.Update.Set("cuisine", "Coffee (Chain)") );
대체 작업
문서 의 필드를 바꾸려면 BulkWriteReplaceOneModel<TDocument> 클래스의 인스턴스 를 만듭니다. BulkWriteReplaceOneModel<TDocument> 생성자는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| The database and collection to insert the BSON document into. |
| The query filter that specifies the criteria used to match documents in your collection. The |
| 대체 문서는 대상 문서에 삽입할 필드와 값을 지정합니다. |
| |
| Optional. The index to use to scan for documents. See the MongoDB Server manual for more information. |
| Optional. Specifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information. |
다음 예시 에서 BulkWriteReplaceOneModel<BsonDocument> 객체는 sample_restaurants.restaurants 및 sample_mflix.movies 컬렉션에 대한 바꾸기 작업을 나타냅니다.
var restaurantReplacement = new BulkWriteReplaceOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234"), new BsonDocument{ { "name", "Mongo's Pizza" }, { "cuisine", "Pizza" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ); var movieReplacement = new BulkWriteReplaceOneModel<BsonDocument>( "sample_mflix.movies", Builders<BsonDocument>.Filter.Eq("title", "Insomnia"), new BsonDocument{ { "name", "Loving Sylvie" }, { "year", 1999 } } );
삭제 작업
문서 를 삭제 하려면 BulkWriteDeleteOneModel<TDocument> 클래스의 인스턴스 를 만듭니다. BulkWriteDeleteOneModel<TDocument> 생성자는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| The database and collection to insert the BSON document into. |
| The query filter that specifies the criteria used to match documents in your collection. The |
| |
| Optional. The index to use to scan for documents. See the MongoDB Server manual for more information. |
다음 코드 예시 에서 BulkWriteDeleteOneModel<BsonDocument> 객체는 sample_restaurants.restaurants 및 sample_mflix.movies 컬렉션에 대한 삭제 작업을 나타냅니다.
var restaurantToDelete = new BulkWriteDeleteOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678") ); var movieToDelete = new BulkWriteDeleteOneModel<BsonDocument>( "sample_mflix.movies", Builders<BsonDocument>.Filter.Eq("title", "Mr. Nobody") );
여러 문서를 삭제 하려면 BulkWriteDeleteManyModel<TDocument> 클래스의 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. DeleteMany 작업은 쿼리 필터하다 와 일치하는 모든 문서를 제거합니다.
다음 코드 예시 에서 BulkWriteDeleteManyModel<BsonDocument> 객체 는 sample_restaurants.restaurants 컬렉션 에 대한 삭제 작업을 나타냅니다. 이 작업은 name 필드 값이 "Mongo's Deli" 인 모든 문서를 일치시키고 삭제합니다.
var deleteManyModel = new BulkWriteDeleteManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli") );
대량 작업 수행
수행하려는 각 작업에 대해 BulkWriteModel 인스턴스 를 정의한 후 IReadOnlyList 인터페이스를 구현하는 클래스의 인스턴스 를 만듭니다. BulkWriteModel 객체를 이 IReadOnlyList에 추가한 다음 IReadOnlyList 를 BulkWrite() 또는 BulkWriteAsync() 메서드에 전달합니다. 기본값 으로 이러한 메서드는 컬렉션 에 정의된 순서대로 작업을 실행 합니다.
팁
IReadOnlyList
Array 및 List 은 IReadOnlyList 인터페이스를 구현 하는 두 가지 일반적인 클래스입니다.
동기 BulkWrite() 메서드 및 비동기 BulkWriteAsync() 메서드를 사용하여 여러 네임스페이스에서 대량 쓰기 (write) 작업을 수행하는 방법을 보려면 다음 탭에서 선택합니다.
var client = new MongoClient("mongodb://localhost:27017"); var restaurantNamespace = "sample_restaurants.restaurants"; var movieNamespace = "sample_mflix.movies"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( restaurantNamespace, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( movieNamespace, new BsonDocument{ { "name", "Sarah's Secret" }, { "year", 1988 } } ), new BulkWriteUpdateManyModel<BsonDocument>( restaurantNamespace, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( movieNamespace, Builders<BsonDocument>.Filter.Eq("title", "House") ) }; var result = client.BulkWrite(bulkWriteModels); Console.WriteLine(result);
var client = new MongoClient("mongodb://localhost:27017"); var restaurantNamespace = "sample_restaurants.restaurants"; var movieNamespace = "sample_mflix.movies"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( restaurantNamespace, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( movieNamespace, new BsonDocument{ { "name", "Sarah's Secret" }, { "year", 1988 } } ), new BulkWriteUpdateManyModel<BsonDocument>( restaurantNamespace, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( movieNamespace, Builders<BsonDocument>.Filter.Eq("title", "House") ) }; var result = await client.BulkWriteAsync(bulkWriteModels); Console.WriteLine(result);
앞의 코드 예제는 다음과 같은 출력을 생성합니다.
BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True)
대량 쓰기 사용자 지정
BulkWrite() 또는 BulkWriteAsync() 메서드를 호출할 때 ClientBulkWriteOptions 클래스의 인스턴스 를 전달할 수 있습니다. ClientBulkWriteOptions 클래스에는 대량 쓰기 (write) 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 다음 속성이 포함되어 있습니다.
속성 | 설명 |
|---|---|
| Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual. |
| A comment to attach to the operation, in the form of a |
|
|
| A map of parameter names and values, in the form of a |
| 작업이 반환하는 |
|
|
다음 코드 예제에서는 ClientBulkWriteOptions 객체 사용하여 대량 쓰기 (write) 작업을 사용자 지정합니다.
반환 값
BulkWrite() 및 BulkWriteAsync() 메서드는 다음 속성을 포함하는 ClientBulkWriteResult 객체 를 반환합니다.
속성 | 설명 |
|---|---|
| 서버가 일괄 쓰기 (write) 작업을 인식했는지 여부를 나타냅니다. 이 속성의 값이 |
| 성공적인 각 삭제 작업의 결과(있는 경우)가 포함된 |
| 삭제된 문서 수(있는 경우). |
| 성공적인 각 삽입 작업의 결과를 포함하는 |
| 삽입된 문서 수입니다(있는 경우). |
| 적용 가능한 경우 업데이트와 일치한 문서의 수. |
| 수정된 문서 수입니다(있는 경우). |
| 성공적인 각 업데이트 작업의 결과를 포함하는 |
| 업서트된 문서 수(있는 경우)입니다. |
예외 처리
대량 쓰기 (write) 작업의 작업 중 하나라도 실패하면 .NET/ C# 드라이버 는 ClientBulkWriteException 를 발생시키고 더 이상의 작업을 수행하지 않습니다.
ClientBulkWriteException 객체 에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
|---|---|
| The connection identifier. |
| 오류 메시지입니다. |
| A dictionary of errors that occurred during the bulk write operation. |
| The results of any successful operations performed before the exception was thrown. |
| Write concern errors that occurred during execution of the bulk write operation. |
| The inner exception. |
데이터 정렬
작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스를 만듭니다.
다음 표에서는 Collation 생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 도 나열되어 있습니다.
Parameter | 설명 | 클래스 속성 |
|---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual. |
|
| (선택 사항) 대/소문자 비교 포함 여부를 지정합니다. |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. |
|
| (Optional) Specifies the level of comparison to perform, as defined in the ICU documentation. |
|
| (선택 사항) |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison. |
|
| (Optional) Specifies which characters the driver considers ignorable when the |
|
| (Optional) Specifies whether the driver normalizes text as needed. |
|
| (선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다. |
|
데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.
추가 정보
개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.
클라이언트 대량 쓰기