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

대량 쓰기 작업

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

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

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

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

  • 클라이언트: 애플리케이션 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>

다음 섹션에서는 이전 클래스의 인스턴스를 만들고 사용하여 대량 쓰기 (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

작업이 문서 수준 유효성 검사를 우회할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 수동의 스키마 유효성 검사 를 참조하세요.
기본값은 False입니다.

Comment

BsonValue 형식으로 작업에 첨부할 주석입니다. 자세한 내용은 MongoDB Server 매뉴얼의 삭제 명령 필드 가이드를 참조하세요.

IsOrdered

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

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

Let

BsonDocument 형식의 매개변수 이름과 값의 맵입니다. 값은 문서 필드를 참조하지 않는 상수 또는 닫힌 표현식이어야 합니다. 자세한 내용은 MongoDB Server 매뉴얼의 let 성명서 참조하세요.

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

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

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

Parameter
설명

collectionNamespace

데이터베이스 및 컬렉션에 BSON 문서를 삽입합니다.

데이터 유형: string 또는 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

데이터베이스 및 컬렉션에 BSON 문서를 삽입합니다.

데이터 유형: string 또는 CollectionNamespace

filter

컬렉션의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터. UpdateOne 작업은 쿼리 필터와 일치하는 첫 번째 문서만 업데이트합니다.

데이터 유형: FilterDefinition<TDocument>

update

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

데이터 유형: UpdateDefinition<TDocument>

collation

선택 사항. 결과를 정렬할 때 사용할 언어 데이터 정렬입니다. 자세한 내용은 이 페이지의 "데이터 정렬 " 섹션을 참조하십시오.

데이터 유형: 데이터 정렬
기본값: null

hint

선택 사항. 문서를 스캔할 때 사용할 인덱스입니다. 자세한 내용은 MongoDB Server 문서 를 참조하세요.

데이터 유형: BsonValue
기본값: null

isUpsert

선택 사항. 쿼리 필터와 일치하는 문서가 없는 경우 업데이트 작업에서 업서트 작업을 수행할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 서버 서리즈 를 참조하세요.

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

arrayFilters

배열 필드에서 업데이트 작업을 위해 수정할 배열 요소를 지정합니다. 자세한 내용은 MongoDB Server 서버 설명서 를 참조하세요.

데이터 유형: IEnumerable<ArrayFilterDefinition>
기본값: 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

데이터베이스 및 컬렉션에 BSON 문서를 삽입합니다.

데이터 유형: string 또는 CollectionNamespace

filter

컬렉션의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터. UpdateOne 작업은 쿼리 필터와 일치하는 첫 번째 문서만 업데이트합니다.

데이터 유형: FilterDefinition<TDocument>

replacement

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

데이터 유형: TDocument

collation

선택 사항. 결과를 정렬할 때 사용할 언어 데이터 정렬입니다. 자세한 내용은 이 페이지의 "데이터 정렬 " 섹션을 참조하십시오.

데이터 유형: 데이터 정렬
기본값: null

hint

선택 사항. 문서를 스캔할 때 사용할 인덱스입니다. 자세한 내용은 MongoDB Server 문서 를 참조하세요.

데이터 유형: BsonValue
기본값: null

isUpsert

선택 사항. 쿼리 필터와 일치하는 문서가 없는 경우 업데이트 작업에서 업서트 작업을 수행할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 서버 서리즈 를 참조하세요.

데이터 유형: boolean
기본값: 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

데이터베이스 및 컬렉션에 BSON 문서를 삽입합니다.

데이터 유형: string 또는 CollectionNamespace

filter

컬렉션의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터. DeleteOne 작업은 쿼리 필터와 일치하는 첫 번째 문서만 삭제합니다.

데이터 유형: FilterDefinition<TDocument>

collation

선택 사항. 결과를 정렬할 때 사용할 언어 데이터 정렬입니다. 자세한 내용은 이 페이지의 "데이터 정렬 " 섹션을 참조하십시오.

데이터 유형: 데이터 정렬
기본값: null

hint

선택 사항. 문서를 스캔할 때 사용할 인덱스입니다. 자세한 내용은 MongoDB Server 문서 를 참조하세요.

데이터 유형: BsonValue
기본값: 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

작업이 문서 수준 유효성 검사를 우회할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 수동의 스키마 유효성 검사 를 참조하세요.
기본값은 false입니다.

Comment

BsonValue 형식으로 작업에 첨부할 주석입니다. 자세한 내용은 MongoDB Server 매뉴얼의 삭제 명령 필드 가이드를 참조하세요.

IsOrdered

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

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

Let

BsonDocument 형식의 매개변수 이름과 값의 맵입니다. 값은 문서 필드를 참조하지 않는 상수 또는 닫힌 표현식이어야 합니다. 자세한 내용은 MongoDB Server 매뉴얼의 let 성명서 참조하세요.

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

연결 식별자.

데이터 유형: ConnectionId

message

오류 메시지입니다.

데이터 유형: string

writeErrors

대량 쓰기 작업 중에 발생한 오류 사전입니다.

데이터 유형: IReadOnlyDictionary<int, WriteError>

partialResult

예외가 발생하기 전에 수행된 모든 성공적인 작업의 결과.

데이터 유형: ClientBulkWriteResult

writeConcernErrors

일괄 쓰기 (bulk write) 작업 수행 중에 발생한 쓰기 고려 (write concern) 오류.

데이터 유형: IReadOnlyList<MongoWriteConcernException>

innerException

내부 예외.

데이터 유형: 예외

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

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

Parameter
설명
클래스 속성

locale

ICU(International Components for Unicode) 국가 및 언어 설정을 지정합니다. 지원되는 국가 및 언어 설정 목록은 MongoDB Server Manual의 데이터 정렬 국가 및 언어 설정 및 기본 매개변수 를 참조하세요.

간단한 이진 비교를 사용하려면 Collation.Simple 정적 속성을 사용하여 locale"simple"으로 설정된 Collation 객체를 반환합니다.
데이터 유형: string

Locale

caseLevel

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

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

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

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

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

CaseLevel

caseFirst

(선택 사항) 3차 수준 비교 시 대소문자 차이의 정렬 순서를 지정합니다.

데이터 유형: CollationCaseFirst
기본값: CollationCaseFirst.Off

CaseFirst

strength

(선택 사항) ICU 문서에 정의된 대로 수행할 비교 수준을 지정합니다.

데이터 유형: CollationStrength
기본값: CollationStrength.Tertiary

Strength

numericOrdering

(선택 사항) 드라이버가 숫자 문자열을 숫자로 비교할지 여부를 지정합니다.

이 인수가 true이면 드라이버는 숫자 문자열을 숫자로 비교합니다. 예시를 들어, 문자열 "10"과 "2"를 비교할 때 드라이버는 값을 10 과 2로 간주하고 10 가 더 큰 값이라고 판단합니다.

이 인수가 false 이거나 제외되면 드라이버는 숫자 문자열을 문자열로 비교합니다. 예시를 들어, 문자열 "10"과 "2"를 비교할 때 드라이버는 한 번에 한 문자씩 비교합니다. "1"가 "2"보다 작으므로 드라이버는 "10"가 "2"보다 작다고 판단합니다.

자세한 내용은 MongoDB Server 수동의 데이터 정렬 제한 을 참조하세요.

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

NumericOrdering

alternate

(선택 사항) 비교를 위해 드라이버가 공백과 구두점을 기본 문자로 간주할지 여부를 지정합니다.

데이터 유형: CollationAlternate
기본값: CollationAlternate.NonIgnorable (공백과 구두점은 기본 문자로 간주됨)

Alternate

maxVariable

(선택 사항) 인수가 일 때 운전자 무시할 수 있는 것으로 간주하는 alternate CollationAlternate.Shifted문자를 지정합니다.

데이터 유형: CollationMaxVariable 기본값:(
CollationMaxVariable.Punctuation 운전자 구두점 및 공백 무시)

MaxVariable

normalization

(선택 사항) 운전자 필요에 따라 텍스트를 정규화할지 여부를 지정합니다.

대부분의 텍스트에는 정규화가 필요하지 않습니다. 정규화에 대한 자세한 내용은 ICU 문서를 참조하세요.

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

Normalization

backwards

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

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

Backwards

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

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

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