Bulk Write Operations
On this page
Overview
In this guide, you can learn how to perform multiple write operations in a single database call by using bulk write operations.
Consider a scenario in which you want to insert a document into a collection, update multiple other documents, then delete a document. If you use individual methods, each operation requires its own database call. Instead, you can use a bulk operation to reduce the number of calls to the database.
Sample Data
The examples in this guide use the restaurants
collection in the sample_restaurants
database from the Atlas sample datasets. To access this collection
from your C++ application, instantiate a mongocxx::client
that connects to an Atlas cluster
and assign the following values to your db
and collection
variables:
auto db = client["sample_restaurants"]; auto collection = db["restaurants"];
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
Create a Bulk Write Instance
Before running a bulk write operation, call the create_bulk_write()
method on
a collection. This method returns an instance of the mongocxx::bulk_write
class that you can use to store instructions about which types of bulk writes to
perform.
The following example calls the create_bulk_write()
method on the restaurants
collection:
auto bulk = collection.create_bulk_write();
You can then append write models to your mongocxx::bulk_write
instance to define
the bulk operation. For more information, see the following Define the Write Operations
section.
Define the Write Operations
For each write operation you want to perform, create an instance of one of the following model classes:
mongocxx::model::insert_one
mongocxx::model::update_one
mongocxx::model::update_many
mongocxx::model::replace_one
mongocxx::model::delete_one
mongocxx::model::delete_many
Then, append each write model to the mongocxx::bulk_write
instance returned
by the create_bulk_write()
method.
The following sections show how to create and use instances of the preceding write model classes.
Insert Operations
To perform an insert operation, create an instance of the mongocxx::model::insert_one
class and specify the document you want to insert. Then, append the model instance
to an instance of the mongocxx::bulk_write
class.
The following example creates an instance of mongocxx::model::insert_one
and appends
it to a mongocxx::bulk_write
instance called bulk
:
auto insert_doc = make_document(kvp("name", "Mongo's Deli"), kvp("cuisine", "Sandwiches"), kvp("borough", "Manhattan"), kvp("restaurant_id", "1234")); mongocxx::model::insert_one insert_op{insert_doc.view()}; bulk.append(insert_op);
To insert multiple documents, create an instance of mongocxx::model::insert_one
for each document.
Update Operations
To update a document, create an instance of mongocxx::model::update_one
. This model
instructs the driver to update the first document that matches your query filter. Then,
append the model instance to an instance of the mongocxx::bulk_write
class.
Pass the following arguments to the mongocxx::model::update_one
model:
Query filter document, which specifies the criteria used to match documents in your collection.
Update document, which specifies the kind of update to perform. For more information about update operations, see the Field Update Operators guide in the MongoDB Server manual.
The following example creates an instance of mongocxx::model::update_one
and appends
it to a mongocxx::bulk_write
instance called bulk
:
auto filter_doc = make_document(kvp("name", "Mongo's Deli")); auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads")))); mongocxx::model::update_one update_op{filter_doc.view(), update_doc.view()}; bulk.append(update_op);
To update multiple documents, create an instance of mongocxx::model::update_many
and pass in the same arguments. This model instructs the driver to update all documents
that match your query filter.
The following example creates an instance of mongocxx::model::update_many
and appends
it to bulk
:
auto filter_doc = make_document(kvp("name", "Mongo's Deli")); auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads")))); mongocxx::model::update_many update_op{filter_doc.view(), update_doc.view()}; bulk.append(update_op);
Replace Operations
A replace operation removes all fields and values of a specified document and
replaces them with new ones. To perform a replace operation, create an instance
of the mongocxx::model::replace_one
class and pass it a query filter and
the fields and values you want to store in the matching document. Then, append
the model instance to an instance of the mongocxx::bulk_write
class.
The following example creates an instance of mongocxx::model::replace_one
and appends
it to a mongocxx::bulk_write
instance called bulk
:
auto filter_doc = make_document(kvp("restaurant_id", "1234")); auto replace_doc = make_document(kvp("name", "Mongo's Deli"), kvp("cuisine", "Sandwiches and Salads"), kvp("borough", "Brooklyn"), kvp("restaurant_id", "5678")); mongocxx::model::replace_one replace_op{filter_doc.view(), replace_doc.view()}; bulk.append(replace_op);
To replace multiple documents, you must create a new instance of mongocxx::model::replace_one
for each document.
Delete Operations
To delete a document, create an instance of the mongocxx::model::delete_one
class and
pass in a query filter specifying the document you want to delete. This model instructs
the driver to delete only the first document that matches your query filter. Then, append
the model instance to an instance of the mongocxx::bulk_write
class.
The following example creates an instance of mongocxx::model::delete_one
and appends
it to a mongocxx::bulk_write
instance called bulk
:
auto filter_doc = make_document(kvp("restaurant_id", "5678")); mongocxx::model::delete_one delete_op{filter_doc.view()}; bulk.append(delete_op);
To delete multiple documents, create an instance of the mongocxx::model::delete_many
class and pass in a query filter specifying the document you want to delete. This model
instructs the driver to delete all documents that match your query filter.
The following example creates an instance of mongocxx::model::delete_many
and appends
it to bulk
:
auto filter_doc = make_document(kvp("borough", "Manhattan")); mongocxx::model::delete_many delete_op{filter_doc.view()}; bulk.append(delete_op);
Run the Bulk Operation
To run a bulk operation, call the execute()
method on an instance of the
mongocxx::bulk_write
class that contains your write models. By default, the
execute()
method runs the operations in the order they're appended to the
mongocxx::bulk_write
instance.
The following example performs the insert,
update, replace,
and delete operations specified in the preceding
sections of this guide by appending each corresponding write model to an instance
of mongocxx::bulk_write
and calling the execute()
method. Then, it prints
the number of modified documents:
auto bulk = collection.create_bulk_write(); // Specifies documents to insert, update, replace, or delete auto insert_doc = make_document(kvp("name", "Mongo's Deli"), kvp("cuisine", "Sandwiches"), kvp("borough", "Manhattan"), kvp("restaurant_id", "1234")); auto update_filter = make_document(kvp("name", "Mongo's Deli")); auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads")))); auto replace_filter = make_document(kvp("restaurant_id", "1234")); auto replace_doc = make_document(kvp("name", "Mongo's Deli"), kvp("cuisine", "Sandwiches and Salads"), kvp("borough", "Brooklyn"), kvp("restaurant_id", "5678")); auto delete_filter = make_document(kvp("borough", "Manhattan")); // Creates write models for each write operation using the preceding documents mongocxx::model::insert_one insert_op{insert_doc.view()}; mongocxx::model::update_many update_op{update_filter.view(), update_doc.view()}; mongocxx::model::replace_one replace_op{replace_filter.view(), replace_doc.view()}; mongocxx::model::delete_many delete_op{delete_filter.view()}; // Appends each write model to the bulk operation bulk.append(insert_op); bulk.append(update_op); bulk.append(replace_op); bulk.append(delete_op); // Runs the bulk operation auto result = bulk.execute(); std::cout << "Modified documents: " << result->modified_count() << std::endl;
Modified documents: 2
If any of the write operations fail, the C++ driver raises a
mongocxx::bulk_write_exception
and does not perform any further operations.
Tip
To learn more about the modified_count()
function, see the Return Value
section of this guide.
Customize Bulk Write Operations
You can modify the behavior of the create_bulk_write()
method by passing
an instance of the mongocxx::options::bulk_write
class as a parameter. The following
table describes the fields you can set in a mongocxx::options::bulk_write
instance:
Field | Description |
---|---|
ordered | 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.Defaults to true . |
bypass_document_validation | Specifies whether the operation bypasses document-level validation. For more
information, see Schema
Validation in the MongoDB
Server manual. Defaults to false . |
write_concern | Specifies the write concern for the bulk operation. For more information, see
Write Concern in the MongoDB Server manual. |
comment | Attaches a comment to the operation. For more information, see the delete command
fields guide in the
MongoDB Server manual. |
let | Specifies a document with a list of values to improve operation readability. 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. |
The following example calls the create_bulk_write()
method from the
Create a Bulk Write Instance example on this page, but sets the ordered
field
of a mongocxx::options::bulk_write
instance to false
:
mongocxx::options::bulk_write opts; opts.ordered(false); auto bulk = collection.create_bulk_write(opts);
If any of the write operations in an unordered bulk write fail, the C++ driver reports the errors only after attempting all operations.
Note
Unordered bulk operations do not guarantee order of execution. The order can differ from the way you list them to optimize the runtime.
Return Value
The execute()
method returns an instance of the mongocxx::result::bulk_write
class.
The mongocxx::result::bulk_write
class contains the following member functions:
Function | Description |
---|---|
deleted_count() | Returns the number of documents deleted, if any. |
inserted_count() | Returns the number of documents inserted, if any. |
matched_count() | Returns the number of documents matched for an update, if applicable. |
modified_count() | Returns the number of documents modified, if any. |
upserted_count() | Returns the number of documents upserted, if any. |
upserted_ids() | Returns a map of the operation's index to the _id of the upserted documents, if
applicable. |
Additional Information
To learn how to perform individual write operations, see the following guides:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: