AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

대량 쓰기 작업

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

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

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

  • Collection: You can use the IMongoCollection.BulkWrite() or IMongoCollection.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.restaurantssample_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, 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

True인 경우 드라이버는 제공된 순서대로 쓰기 (write) 작업을 수행합니다. 오류가 발생하면 나머지 작업은 수행되지 않습니다.

False인 경우 드라이버는 임의 순서로 작업을 수행하고 모든 작업을 수행하려고 시도합니다. 순서가 지정되지 않은 대량 쓰기 (write)의 쓰기 (write) 작업 중 하나라도 실패하면 드라이버는 모든 작업을 시도한 후에만 오류를 보고합니다.
기본값은 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

서버가 일괄 쓰기 (write) 작업을 인식했는지 여부를 나타냅니다. 이 속성의 값이 False 이고 BulkWriteResult 객체의 다른 속성에 액세스하려고 하면 드라이버가 예외를 발생시킵니다.

DeletedCount

삭제된 문서 수(있는 경우).

InsertedCount

삽입된 문서 수입니다(있는 경우).

MatchedCount

적용 가능한 경우 업데이트와 일치한 문서의 수.

ModifiedCount

수정된 문서 수입니다(있는 경우).

IsModifiedCountAvailable

수정된 카운트를 사용할 수 있는지 여부를 나타냅니다.

Upserts

업서트 작업이 수행된 각 요청에 대한 정보가 포함된 목록입니다.

RequestCount

불크 작업의 요청 수.

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

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

document

컬렉션에 삽입할 문서입니다.

데이터 유형: 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.

Data Type: FilterDefinition<TDocument>

update

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

Data Type: UpdateDefinition<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

arrayFilters

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

Data Type: IEnumerable<ArrayFilterDefinition>
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.

Data Type: FilterDefinition<TDocument>

replacement

대체 문서는 대상 문서에 삽입할 필드와 값을 지정합니다.

데이터 유형: 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.

Data Type: FilterDefinition<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

다음 코드 예시 에서 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

true인 경우 드라이버는 제공된 순서대로 쓰기 (write) 작업을 수행합니다. 오류가 발생하면 나머지 작업은 수행되지 않습니다.

false인 경우 드라이버는 임의 순서로 작업을 수행하고 모든 작업을 수행하려고 시도합니다. 순서가 지정되지 않은 대량 쓰기 (write)의 쓰기 (write) 작업 중 하나라도 실패하면 드라이버는 모든 작업을 시도한 후에만 오류를 보고합니다.
기본값은 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

작업이 반환하는 ClientBulkWriteResult 객체에 각 성공적인 쓰기 (write) 작업에 대한 세부 결과가 포함되는지 지정합니다.
기본값은 false입니다.

WriteConcern

WriteConcern 열거형의 값으로서 쓰기 작업에 사용할 쓰기 고려 (write concern).
기본적으로 작업이 실행되는 컬렉션의 쓰기 고려 (write concern)로 설정됩니다.

다음 코드 예제에서는 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

서버가 일괄 쓰기 (write) 작업을 인식했는지 여부를 나타냅니다. 이 속성의 값이 false 이고 ClientBulkWriteResult 객체의 다른 속성에 액세스하려고 하면 드라이버가 예외를 발생시킵니다.

DeleteResults

성공적인 각 삭제 작업의 결과(있는 경우)가 포함된 IReadOnlyDictionary<int, BulkWriteDeleteResult> 객체 .

DeletedCount

삭제된 문서 수(있는 경우).

InsertResults

성공적인 각 삽입 작업의 결과를 포함하는 IReadOnlyDictionary<int, BulkWriteInsertOneResult> 객체(있는 경우)

InsertedCount

삽입된 문서 수입니다(있는 경우).

MatchedCount

적용 가능한 경우 업데이트와 일치한 문서의 수.

ModifiedCount

수정된 문서 수입니다(있는 경우).

UpsertResults

성공적인 각 업데이트 작업의 결과를 포함하는 IReadOnlyDictionary<int, BulkWriteUpdateResult> 객체(있는 경우)

UpsertedCount

업서트된 문서 수(있는 경우)입니다.

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

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

속성
설명

connectionId

The connection identifier.

Data Type: ConnectionId

message

오류 메시지입니다.

데이터 유형: 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.

Data Type: ClientBulkWriteResult

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

(선택 사항) 대/소문자 비교 포함 여부를 지정합니다.

이 인수가 true인 경우 드라이버의 동작은 strength 인수의 값에 따라 달라집니다.

- strengthCollationStrength.Primary인 경우 드라이버는 기본 문자와 대소문자를 비교합니다.
- strengthCollationStrength.Secondary인 경우 드라이버는 기본 문자, 발음 부호, 기타 세컨더리 차이 및 대소문자를 비교합니다.
- strength 이 기타 값인 경우 이 인수는 무시됩니다.

이 인수가 false인 경우 드라이버는 Primary 또는 Secondary 수준의 강도에서 대소문자 비교를 포함하지 않습니다.

데이터 유형: boolean
기본값: false

CaseLevel

caseFirst

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

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

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

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(선택 사항)

true102운전자 숫자 문자열을 숫자로 비교할지 여부를 지정합니다.10 이 2 인수가 10 이면

false 운전자 숫자 문자열을 숫자로 비교합니다. 예시 들어,10" " 및 & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & &2& & & & & & & & &1& & & & & & &2& & & & & & & & & & & & " & " 이 인수가10이거나 제외되면 운전자 숫자 문자열을2문자열로 비교합니다. 예시 들어, " " 및 & "", 운전자 한 번에 한 문자씩 비교합니다. " " 가 " "보다 작으면 운전자 " " " "보다 작아야 합니다.

자세한 내용은 MongoDB Server 매뉴얼에서 데이터 정렬 제한을 참조하세요.

데이터 유형: boolean
기본값: false

NumericOrdering

alternate

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

Data Type: CollationAlternate
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.

Data Type: CollationMaxVariable
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

(선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다.

데이터 유형: boolean
기본값: false

Backwards

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

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

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