Bulk Write Operations
On this page
Overview
This guide shows you how to use the .NET/C# Driver to perform bulk write operations
from your MongoClient
instance. A bulk write operation is a single database call
that performs multiple write operations on one or more MongoDB collections. This is more
efficient than performing multiple individual write operations because it reduces the
number of round trips between your application and the database.
Sample Data
The examples in this guide use the sample_restaurants.restaurants
collection
from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Quick Start tutorial.
Define the Write Operations
For each write operation you want to perform, create an instance of one of
the following BulkWriteModel
classes:
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.
Tip
Bulk Write Operations with POCOs
The examples in this guide use the BsonDocument
type for the TDocument
type
in all generic classes. You can also use a Plain Old CLR Object (POCO) for these
classes. To do so, you must define a class that represents the documents in your
collection. The class must have properties that match the fields in your documents.
For more information, see POCOs.
Insert Operations
To perform an insert operation, create an instance of the
BulkWriteInsertOneModel<TDocument>
class.
The BulkWriteInsertOneModel<TDocument>
constructor accepts the following parameters:
Parameter | Description |
---|---|
collectionNamespace | The database and collection to insert the BSON document into. Data Type: string or CollectionNamespace |
document | The document to insert into the collection. Data Type: TDocument |
The following example creates an instance of the BulkWriteInsertOneModel<TDocument>
class. This instance directs the driver to insert a document in which the "name"
field
is "Mongo's Deli"
into the sample_restaurants.restaurants
collection.
var insertOneModel = new BulkWriteInsertOneModel<BsonDocument>( "sample_restaurants.restaurants", new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } );
Tip
Insert Multiple Documents
To insert multiple documents, create an instance of the
BulkWriteInsertOneModel<TDocument>
class for each document you want to insert.
Update Operations
To update a single document, create an instance of the BulkWriteUpdateOneModel<TDocument>
class. The BulkWriteUpdateOneModel<TDocument>
constructor accepts the following
parameters:
Parameter | Description |
---|---|
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
{+mdb+server+} manual
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 |
In the following code example, the BulkWriteUpdateOneModel<BsonDocument>
object
represents an update operation on the sample_restaurants.restaurants
collection.
The operation matches the first document in the collection where the value of the name
field is "Mongo's Deli"
. It then updates the value of the cuisine
field in the
matched document to "Sandwiches and Salads"
.
var updateOneModel = new BulkWriteUpdateOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
To update multiple documents, create an instance of the
BulkWriteUpdateManyModel<TDocument>
class. The constructor for this class
accepts the same parameters as the BulkWriteUpdateOneModel<TDocument>
constructor.
The BulkWriteUpdateManyModel<TDocument>
operation updates all documents that match your query filter.
In the following code example, the BulkWriteUpdateManyModel<BsonDocument>
object
represents an update operation on the sample_restaurants.restaurants
collection.
The operation matches all documents in the collection where
the value of the name
field is "Mongo's Deli"
. It then updates
the value of the cuisine
field to "Sandwiches and Salads"
.
var updateManyModel = new BulkWriteUpdateManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
Replace Operations
To replace the fields in a document, create an instance of the
BulkWriteReplaceOneModel<TDocument>
class. The BulkWriteReplaceOneModel<TDocument>
constructor accepts the following parameters:
Parameter | Description |
---|---|
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 | 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 MongoDB Server manual
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 |
In the following example, the BulkWriteReplaceOneModel<BsonDocument>
object
represents a replace operation on the sample_restaurants.restaurants
collection.
The operation matches the document in the collection
where the value of the restaurant_id
field is "1234"
. It then
removes all fields other than _id
from this document, and sets new values in the
name
, cuisine
, borough
, and restaurant_id
fields.
var replaceOneModel = 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" } } );
Tip
Replace Multiple Documents
To replace multiple documents, create an instance of the
BulkWriteReplaceOneModel<TDocument>
class for each document you want to replace.
Delete Operations
To delete a document, create an instance of the BulkWriteDeleteOneModel<TDocument>
class. The BulkWriteDeleteOneModel<TDocument>
constructor accepts the following
parameters:
Parameter | Description |
---|---|
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 MongoDB Server manual
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 |
In the following code example, the BulkWriteDeleteOneModel<BsonDocument>
object
represents a delete operation on the sample_restaurants.restaurants
collection.
The operation matches and deletes the first document
where the value of the restaurant_id
field is "5678"
.
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678") );
To delete multiple documents, create an instance of the BulkWriteDeleteManyModel<TDocument>
class and pass a query filter that specifies the document that you want to delete.
The DeleteMany
operation removes all documents that match your
query filter.
In the following code example, the BulkWriteDeleteManyModel<BsonDocument>
object
represents a delete operation on the sample_restaurants.restaurants
collection.
The operation matches and deletes all documents
where the value of the name
field is "Mongo's Deli"
.
var deleteManyModel = new BulkWriteDeleteManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli") );
Run the Write Operations
After you define a BulkWriteModel
instance for each operation that you want to perform,
create an instance of a class that implements the IReadOnlyList
interface. Add your
BulkWriteModel
objects to this IReadOnlyList
, then pass the IReadOnlyList
to the BulkWrite()
or BulkWriteAsync()
method. By default, these methods run
the operations in the order they're defined in the collection.
Tip
IReadOnlyList
Array
and List
are two common classes that implement the IReadOnlyList
interface.
Select from the following tabs to view how to use the asynchronous
BulkWriteAsync()
method and the synchronous BulkWrite()
method to
perform a bulk write operation.
var client = new MongoClient("mongodb://localhost:27017"); var collection = "sample_restaurants.restaurants"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new BulkWriteUpdateManyModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = await client.BulkWriteAsync(bulkWriteModels); Console.WriteLine("Bulk write results: " + results);
var client = new MongoClient("mongodb://localhost:27017"); var collection = "sample_restaurants.restaurants"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new BulkWriteUpdateManyModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = client.BulkWrite(bulkWriteModels); Console.WriteLine("Bulk write results: " + results);
The preceding code examples produce the following output:
BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True)
Customize Bulk Write Operations
When you call the BulkWrite()
or BulkWriteAsync()
method, you can pass an
instance of the ClientBulkWriteOptions
class. The ClientBulkWriteOptions
class
contains the following properties, which represent options you can use to configure the
bulk write operation:
Property | Description |
---|---|
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. |
The following code examples use a ClientBulkWriteOptions
object to customize
a delete operation:
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 results = await client.BulkWriteAsync(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 results = client.BulkWrite(deleteOneModel, clientBulkWriteOptions);
Return Value
The BulkWrite()
and BulkWriteAsync()
methods return a ClientBulkWriteResult
object that contains the following properties:
Property | Description |
---|---|
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. |
Handling Exceptions
If any of the operations in a bulk write operation fail, the .NET/C# Driver throws a
ClientBulkWriteException
and does not perform any further operations.
A ClientBulkWriteException
object contains the following properties:
Property | Description |
---|---|
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. Data Type: ClientBulkWriteResult |
writeConcernErrors | Write concern errors that occurred during execution of the bulk write operation. Data Type: IReadOnlyList<MongoWriteConcernException> |
innerException |
Additional Information
To learn how to perform individual write operations, see the following guides:
To learn more about any of the methods or types discussed in this guide, see the following API documentation: