Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
C#/ .NET 드라이버
/ / /

대량 쓰기 작업

이 가이드 에서는 .NET/ C# 드라이버 사용하여 대량 쓰기 (write) 작업을 수행하는 방법에 학습 합니다. 대량 쓰기 (write) 작업을 사용하면 데이터베이스 에 대한 호출 횟수를 줄이고 여러 쓰기 (write) 작업을 수행할 수 있습니다.

동일한 작업 에 대해 문서를 삽입하고, 문서를 업데이트 하고, 문서를 삭제 해야 하는 상황을 생각해 보세요. 개별 쓰기 (write) 메서드를 사용하여 각 유형의 작업을 수행하는 경우 각 쓰기 (write) 는 데이터베이스 에 별도로 액세스합니다. 대량 쓰기 (write) 작업을 사용하여 애플리케이션 에서 서버 에 대해 수행하는 호출 수를 최적화할 수 있습니다.

IMongoCollection.BulkWrite() 또는 IMongoCollection.BulkWriteAsync() 메서드를 사용하여 단일 컬렉션 에 대해 대량 쓰기 (write) 작업을 수행할 수 있습니다. 각 메서드는 수행할 쓰기 (write) 작업을 설명하는 WriteModel<TDocument> 인스턴스 목록을 사용합니다.

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

수행하려는 각 쓰기 (write) 작업에 대해 다음 WriteModel<TDocument> 클래스 중 하나의 인스턴스 를 만듭니다.

  • DeleteManyModel<TDocument>

  • DeleteOneModel<TDocument>

  • InsertOneModel<TDocument>

  • ReplaceOneModel<TDocument>

  • UpdateManyModel<TDocument>

  • UpdateOneModel<TDocument>

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

POCO를 사용한 대량 쓰기 작업

이 가이드 의 예제에서는 모든 일반 클래스의 TDocument 유형에 BsonDocument 유형을 사용합니다. 이러한 클래스에 POCO(Plain Old CLR Object)를 사용할 수도 있습니다. 이렇게 하려면 컬렉션 의 문서를 나타내는 클래스를 정의해야 합니다. 클래스에는 문서의 필드와 일치하는 속성이 있어야 합니다. 자세한 내용은 POCO를 참조하세요.

삽입 작업을 수행하려면 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 속성 포함되어 있습니다.

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

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

돌아가기

삭제

이 페이지의 내용