Docs Menu
Docs Home
/ / /
C#/ .NET 드라이버
/

대량 쓰기 작업

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

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

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

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

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

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

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>

다음 섹션에서는 이전 클래스의 인스턴스를 만들고 사용하여 대량 쓰기 (write) 작업에서 해당 쓰기 (write) 작업을 수행하는 방법을 보여줍니다. 대량 작업 수행 섹션에서는 모델 목록을 BulkWrite() 또는 BulkWriteAsync() 메서드에 전달하여 대량 작업을 수행하는 방법을 보여 줍니다.

삽입 작업을 수행하려면 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 매뉴얼의 쿼리 및 프로젝션 연산자 를 참조하세요.

  • 수행할 업데이트 설명하는 업데이트 문서 입니다. 업데이트 지정에 대해 자세히 학습 MongoDB Server 매뉴얼에서 업데이트 연산자를 참조하세요.

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, boroughrestaurant_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 인터페이스를 구현하는 클래스의 인스턴스 만듭니다. 이 IEnumerableWriteModel 객체를 추가한 다음 IEnumerableBulkWrite() 또는 BulkWriteAsync() 메서드에 전달합니다. 기본값 으로 이러한 메서드는 목록에 정의된 순서대로 작업을 실행 .

IEnumerable

ArrayListIEnumerable 인터페이스를 구현 하는 두 가지 일반적인 클래스입니다.

동기 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) 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 다음 속성이 포함되어 있습니다.

속성
설명

BypassDocumentValidation

Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to False.

Comment

A comment to attach to the operation, in the form of a BsonValue. For more information, see the delete command fields guide in the MongoDB Server manual.

IsOrdered

If True, the driver performs the write operations in the order provided. If an error occurs, the remaining operations are not attempted.

If False, the driver performs the operations in an arbitrary order and attempts to perform all operations. If any of the write operations in an unordered bulk write fail, the driver reports the errors only after attempting all operations.
Defaults to True.

Let

A map of parameter names and values, in the form of a BsonDocument. 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.

다음 코드 예제에서는 BulkWriteOptions 객체 사용하여 순서가 지정되지 않은 대량 쓰기 (write) 작업을 수행합니다.

var models = new List<WriteModel<BsonDocument>>
{
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
)
};
var options = new BulkWriteOptions
{
IsOrdered = false,
};
collection.BulkWrite(models, options);
var models = new List<WriteModel<BsonDocument>>
{
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
)
};
var options = new BulkWriteOptions
{
IsOrdered = false,
};
await collection.BulkWriteAsync(models, options);

BulkWrite()BulkWriteAsync() 메서드는 다음 속성을 포함하는 BulkWriteResult 객체 를 반환합니다.

속성
설명

IsAcknowledged

Indicates whether the server acknowledged the bulk write operation. If the value of this property is False and you try to access any other property of the BulkWriteResult object, the driver throws an exception.

DeletedCount

The number of documents deleted, if any.

InsertedCount

The number of documents inserted, if any.

MatchedCount

The number of documents matched for an update, if applicable.

ModifiedCount

The number of documents modified, if any.

IsModifiedCountAvailable

Indicates whether the modified count is available.

Upserts

A list that contains information about each request that resulted in an upsert operation.

RequestCount

The number of requests in the bulk operation.

대량 쓰기 (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>

다음 섹션에서는 이전 클래스의 인스턴스를 만들고 사용하여 대량 쓰기 (write) 에서 해당 쓰기 (write) 작업을 수행하는 방법을 보여줍니다. 대량 작업 수행 섹션에서는 모델 목록을 BulkWrite() 또는 BulkWriteAsync() 메서드에 전달하여 대량 작업을 수행하는 방법을 보여 줍니다.

삽입 작업을 수행하려면 BulkWriteInsertOneModel<TDocument> 클래스의 인스턴스 를 만듭니다. BulkWriteInsertOneModel<TDocument> 생성자는 다음 매개변수를 허용합니다.

Parameter
설명

collectionNamespace

document

The document to insert into the collection.

Data Type: TDocument

다음 예시 BulkWriteInsertOneModel<TDocument> 클래스의 인스턴스를 만듭니다. 이러한 인스턴스는 운전자 에 sample_restaurants.restaurantssample_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
설명

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

The query filter that specifies the criteria used to match documents in your collection. The UpdateOne operation updates only the first document that matches the query filter.

update

The update operation you want to perform. For more information about update operations, see Field Update Operators in the MongoDB Server manual.

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

Optional. The index to use to scan for documents. See the MongoDB Server manual for more information.

Data Type: BsonValue
Default: null

isUpsert

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.

Data Type: boolean
Default: false

arrayFilters

Specifies which array elements to modify for an update operation on an array field. See the MongoDB Server manual for more information.

Default: null

다음 코드 예시 에서 BulkWriteUpdateOneModel<BsonDocument> 객체는 sample_restaurants.restaurantssample_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
설명

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

The query filter that specifies the criteria used to match documents in your collection. The UpdateOne operation updates only the first document that matches the query filter.

replacement

The replacement document, which specifies the fields and values to insert in the target document.

Data Type: TDocument

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

Optional. The index to use to scan for documents. See the MongoDB Server manual for more information.

Data Type: BsonValue
Default: null

isUpsert

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.

Data Type: boolean
Default: false

다음 예시 에서 BulkWriteReplaceOneModel<BsonDocument> 객체는 sample_restaurants.restaurantssample_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
설명

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

The query filter that specifies the criteria used to match documents in your collection. The DeleteOne operation deletes only the first document that matches the query filter.

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

Optional. The index to use to scan for documents. See the MongoDB Server manual for more information.

Data Type: BsonValue
Default: null

다음 코드 예시 에서 BulkWriteDeleteOneModel<BsonDocument> 객체는 sample_restaurants.restaurantssample_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에 추가한 다음 IReadOnlyListBulkWrite() 또는 BulkWriteAsync() 메서드에 전달합니다. 기본값 으로 이러한 메서드는 컬렉션 에 정의된 순서대로 작업을 실행 합니다.

IReadOnlyList

ArrayListIReadOnlyList 인터페이스를 구현 하는 두 가지 일반적인 클래스입니다.

동기 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) 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 다음 속성이 포함되어 있습니다.

속성
설명

BypassDocumentValidation

Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to false.

Comment

A comment to attach to the operation, in the form of a BsonValue. For more information, see the delete command fields guide in the MongoDB Server manual.

IsOrdered

If true, the driver performs the write operations in the order provided. If an error occurs, the remaining operations are not attempted.

If false, the driver performs the operations in an arbitrary order and attempts to perform all operations. If any of the write operations in an unordered bulk write fail, the driver reports the errors only after attempting all operations.
Defaults to True.

Let

A map of parameter names and values, in the form of a BsonDocument. 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.

VerboseResult

Specifies whether the ClientBulkWriteResult object returned by the operation includes detailed results for each successful write operation.
Defaults to false.

WriteConcern

The write concern to use for the write operation, as a value from the WriteConcern enum.
Defaults to the write concern of the collection on which the operation is running.

다음 코드 예제에서는 ClientBulkWriteOptions 객체 사용하여 대량 쓰기 (write) 작업을 사용자 지정합니다.

var client = new MongoClient("mongodb://localhost:27017");
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);
var clientBulkWriteOptions = new ClientBulkWriteOptions
{
IsOrdered = false,
WriteConcern = WriteConcern.Unacknowledged,
VerboseResult = true
};
var result = client.BulkWrite(deleteOneModel, clientBulkWriteOptions);
var client = new MongoClient("mongodb://localhost:27017");
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);
var clientBulkWriteOptions = new ClientBulkWriteOptions
{
IsOrdered = false,
WriteConcern = WriteConcern.Unacknowledged,
VerboseResult = true
};
var result = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions);

BulkWrite()BulkWriteAsync() 메서드는 다음 속성을 포함하는 ClientBulkWriteResult 객체 를 반환합니다.

속성
설명

Acknowledged

Indicates whether the server acknowledged the bulk write operation. If the value of this property is false and you try to access any other property of the ClientBulkWriteResult object, the driver throws an exception.

DeleteResults

An IReadOnlyDictionary<int, BulkWriteDeleteResult> object containing the results of each successful delete operation, if any.

DeletedCount

The number of documents deleted, if any.

InsertResults

An IReadOnlyDictionary<int, BulkWriteInsertOneResult> object containing the results of each successful insert operation, if any.

InsertedCount

The number of documents inserted, if any.

MatchedCount

The number of documents matched for an update, if applicable.

ModifiedCount

The number of documents modified, if any.

UpsertResults

An IReadOnlyDictionary<int, BulkWriteUpdateResult> object containing the results of each successful update operation, if any.

UpsertedCount

The number of documents upserted, if any.

대량 쓰기 (write) 작업의 작업 중 하나라도 실패하면 .NET/ C# 드라이버 는 ClientBulkWriteException 를 발생시키고 더 이상의 작업을 수행하지 않습니다.

ClientBulkWriteException 객체 에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

connectionId

The connection identifier.

Data Type: ConnectionId

message

The error message.

Data Type: string

writeErrors

A dictionary of errors that occurred during the bulk write operation.

Data Type: IReadOnlyDictionary<int, WriteError>

partialResult

The results of any successful operations performed before the exception was thrown.

writeConcernErrors

Write concern errors that occurred during execution of the bulk write operation.

Data Type: IReadOnlyList<MongoWriteConcernException>

innerException

The inner exception.

Data Type: Exception

작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스 만듭니다.

다음 표에서는 Collation 생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 나열되어 있습니다.

Parameter
설명
클래스 속성

locale

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.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(Optional) Specifies whether to include case comparison.

When this argument is true, the driver's behavior depends on the value of the strength argument:

- If strength is CollationStrength.Primary, the driver compares base characters and case.
- If strength is CollationStrength.Secondary, the driver compares base characters, diacritics, other secondary differences, and case.
- If strength is any other value, this argument is ignored.

When this argument is false, the driver doesn't include case comparison at strength level Primary or Secondary.

Data Type: boolean
Default: false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If this argument is true, the driver compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the driver treats the values as 10 and 2, and finds 10 to be greater.

If this argument is false or excluded, the driver compares numeric strings as strings. For example, when comparing the strings "10" and "2", the driver compares one character at a time. Because "1" is less than "2", the driver finds "10" to be less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: boolean
Default: false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.

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

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

돌아가기

문서 삭제

이 페이지의 내용