Bulk Write Operations
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, update multiple other documents, then delete a document. If you use individual methods, each operation requires its own database call.
By using a bulk write operation, you can perform multiple write operations in fewer database calls. You can perform bulk write operations at the following levels:
Client: If your application connects to MongoDB Server version 8.0 or later, you can use the
MongoDB\Client::bulkWrite()
method to perform bulk write operations on multiple collections and databases in the same cluster. This method performs all write operations in one database call. To learn more about this feature, see the Mongo.bulkWrite() reference in the MongoDB Server manual.Collection: You can use the
MongoDB\Collection::bulkWrite()
method to perform bulk write operations on a single collection. This method makes a database call for each type of write operation. For example, the method can perform multiple update operations in one call, but makes two separate calls to the database for an insert operation and a replace operation.
Sample Data
The examples in this guide use the sample_restaurants.restaurants
and sample_mflix.movies
collections from the Atlas sample
datasets. To learn how to create a free MongoDB Atlas
cluster and load the sample datasets, see the Get Started with
Atlas guide.
Client Bulk Write
When using PHP library v2.1 and connecting to a deployment
running MongoDB Server 8.0 or later, you can use the
MongoDB\Client::bulkWrite()
method to write to multiple databases
and collections in the same cluster. This method performs all write
operations in a single call.
First, use the MongoDB\ClientBulkWrite
builder to create a
BulkWriteCommand instance that
specifies the write operations to perform. The following code
demonstrates how to create a ClientBulkWrite
instance from a
MongoDB\Collection
instance by using the createWithCollection()
method:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
Then, call one or more of the following write methods on the
ClientBulkWrite
instance to construct the bulk write operation:
deleteOne()
deleteMany()
insertOne()
replaceOne()
updateOne()
updateMany()
To select a different namespace for subsequent write operations, call
the withCollection()
method on the ClientBulkWrite
instance, as
shown in the following code:
$movieCollection = $client->sample_mflix->movies; $bulkWrite = $bulkWrite->withCollection($movieCollection);
The following sections show how to create and use the
ClientBulkWrite
class to specify write operations
in a bulk write. The Perform the Bulk Operation section
demonstrates how to pass the ClientBulkWrite
object to the
bulkWrite()
method to perform the bulk operation.
Insert Operations
To specify an insert operation, call the insertOne()
method on your
ClientBulkWrite
instance.
The following example specifies the insertion of documents into the
sample_restaurants.restaurants
and sample_mflix.movies
collections:
$restaurantCollection = $client->sample_restaurants->restaurants; $movieCollection = $client->sample_mflix->movies; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); $bulkWrite = $bulkWrite->withCollection($movieCollection); $bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]);
Update Operations
To specify an update operation on the first matching document, call the
updateOne()
method on your ClientBulkWrite
instance.
The following example specifies a $set
update to the first document
in the sample_restaurants.restaurants
collection that has a name
value of 'Dandelion Bakery'
:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->updateOne( ['name' => 'Dandelion Bakery'], ['$set' => ['grade' => 'B+']], ['upsert' => true], );
To update multiple documents, call the updateMany()
method. The specified
operation updates all documents that match the query filter.
The following example specifies a $set
update to all matching documents
in the sample_restaurants.restaurants
collection that have a name
value of 'Starbucks'
:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->updateMany( ['name' => 'Starbucks'], ['$set' => ['cuisine' => 'Coffee (Chain)']], );
Replace Operations
To specify an replace operation on the first matching document, call the
replaceOne()
method on your ClientBulkWrite
instance.
The following example specifies a replace operation on the first document
in the sample_restaurants.restaurants
collection that has a name
value of 'Dandelion Bakery'
:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->replaceOne( ['name' => 'Dandelion Bakery'], ['name' => 'Flower Patisserie', 'cuisine' => 'Bakery & Cafe'], );
Delete Operations
To specify an delete operation on the first matching document, call the
deleteOne()
method on your ClientBulkWrite
instance.
The following example specifies the deletion of the first document
in the sample_restaurants.restaurants
collection that has a borough
value of 'Queens'
:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->deleteOne( ['borough' => 'Queens'], );
To delete multiple documents, call the deleteMany()
method. The specified
operation deletes all documents that match the query filter.
The following example specifies the deletion of all documents
in the sample_restaurants.restaurants
collection that have a name
value that contains two consecutive 'p'
characters:
$restaurantCollection = $client->sample_restaurants->restaurants; $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); $bulkWrite->deleteMany( ['name' => ['$regex' => 'p{2,}']], );
Perform the Bulk Operation
After you construct the ClientBulkWrite
instance to specify your
write operations, pass it to the MongoDB\Client::bulkWrite()
method.
By default, these methods run the operations in the order you defined
when constructing ClientBulkWrite
.
The following code demonstrates how to use the bulkWrite()
method
to perform a bulk write operation on multiple namespaces:
$restaurantCollection = $client->sample_restaurants->restaurants; $movieCollection = $client->sample_mflix->movies; // Creates the bulk write command and sets the target namespace. $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); // Specifies insertion of one document. $bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); // Specifies a `$set` update to one document with the upsert option // enabled. $bulkWrite->updateOne( ['name' => 'Dandelion Bakery'], ['$set' => ['grade' => 'B+']], ['upsert' => true], ); // Changes the target namespace. $bulkWrite = $bulkWrite->withCollection($movieCollection); // Specifies insertion of one document. $bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]); // Specifies deletion of documents in which `title` has two consective // 'd' characters. $bulkWrite->deleteMany( ['title' => ['$regex' => 'd{2,}']], ); // Specifies replacement of one document. $bulkWrite->replaceOne( ['runtime' => ['$gte' => 200]], ['title' => 'Seven Samurai', 'runtime' => 203], ); // Performs the bulk write operation. $result = $client->bulkWrite($bulkWrite); // Prints a summary of results. echo 'Inserted documents: ', $result->getInsertedCount(), PHP_EOL; echo 'Modified documents: ', $result->getModifiedCount(), PHP_EOL; echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Inserted documents: 2 Modified documents: 2 Deleted documents: 200
Customize Bulk Write
You can modify the behavior of the client bulk write operation by
passing an array to the ClientBulkWrite
constructor that specifies
option values as a parameter. The following table describes the options
you can set in the array:
Option | Description |
---|---|
| Specifies whether the operation bypasses document validation. This lets you
modify documents that don't meet the schema validation requirements, if any
exist. For more information about schema validation, see Schema
Validation in the MongoDB Server
manual. The default is false . |
| Attaches a comment to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
| 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. |
| If set to true : When a single write fails, the operation stops without
performing the remaining writes and throws an exception.If set to false : When a single write fails, the operation continues to
attempt the remaining write operations, if any, then throws an exception.The default is true . |
| Specifies whether to return verbose results. The default is false . |
The following example creates a ClientBulkWrite
instance and sets
the ordered
option to false
:
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection( $restaurantCollection, ['ordered' => false] );
Note
Unordered Behavior
Unordered bulk operations do not guarantee order of execution. The order can differ from the way you list them to optimize the runtime. Suppose you specify the following write operations in an unordered bulk write:
$bulkWrite->insertOne(['_id' => 4045, 'title' => 'The Green Ray']); $bulkWrite->deleteOne(['_id' => 4045]);
Because the library might run either operation first, the result can show one deleted document or no deleted documents.
You can also pass options when calling the bulkWrite()
method to specify
the client session or the write concern to use for the operation.
Return Value
The MongoDB\Client::bulkWrite()
method returns a MongoDB\BulkWriteCommandResult
object. This class contains the following methods:
Method | Description |
---|---|
| Returns the total number of documents inserted by all
insert operations in the bulk write command. |
| Returns the total number of documents matched by all
update and replace operations in the bulk write command. |
| Returns the total number of documents modified by all update
and replace operations in the bulk write command. |
| Returns the total number of documents upserted by all update
and replace operations in the bulk write command. |
| Return the total number of documents deleted by all delete
operations in the bulk write command. |
| Returns a map of results of each successful insert operation. Each
operation is represented by an integer key, which contains a
document with information corresponding to the operation such
as the inserted _id value. |
| Returns a map of results of each successful update operation. Each
operation is represented by an integer key, which contains a
document with information corresponding to the operation. |
| Returns a map of results of each successful delete operation.
Each operation is represented by an integer key, which contains
a document with information corresponding to the operation. |
| Returns a boolean indicating whether the server acknowledged
the bulk operation. |
Collection Bulk Write
To run a bulk write operation, pass an array of write operations to the
MongoDB\Collection::bulkWrite()
method. Use the following syntax to
specify the write operations:
[ [ 'deleteMany' => [ $filter ] ], [ 'deleteOne' => [ $filter ] ], [ 'insertOne' => [ $document ] ], [ 'replaceOne' => [ $filter, $replacement, $options ] ], [ 'updateMany' => [ $filter, $update, $options ] ], [ 'updateOne' => [ $filter, $update, $options ] ], ]
Tip
To learn more about delete, insert, replace, and update operations, see the guides in the Write Data to MongoDB section.
When you call the bulkWrite()
method, the library automatically runs the
write operations in the order you specify in the array. To learn how to
instruct bulkWrite()
to run the write operations in an arbitrary order,
see the Customize Bulk Write Operation section.
Example
This example runs the following write operations on the restaurants
collection:
Insert operation to insert a document in which the
name
value is'Mongo's Deli'
Update operation to update the
cuisine
field of a document in which thename
value is'Mongo's Deli'
Delete operation to delete all documents in which the
borough
value is'Manhattan'
$restaurantCollection = $client->sample_restaurants->restaurants; $result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ ['name' => 'Mongo\'s Deli'], ['cuisine' => 'Sandwiches'], ['borough' => 'Manhattan'], ['restaurant_id' => '1234'], ], ], [ 'updateOne' => [ ['name' => 'Mongo\'s Deli'], ['$set' => ['cuisine' => 'Sandwiches and Salads']], ], ], [ 'deleteMany' => [ ['borough' => 'Manhattan'], ], ], ] );
Note
When the library runs a bulk operation, it uses the write concern of the target collection. The driver reports all write concern errors after attempting all operations, regardless of execution order.
Customize Bulk Write Operation
You can modify the behavior of the MongoDB\Collection::bulkWrite()
method by
passing an array that specifies option values as a parameter. The following table
describes the options you can set in the array:
Option | Description |
---|---|
| Specifies whether the operation bypasses document validation. This lets you
modify documents that don't meet the schema validation requirements, if any
exist. For more information about schema validation, see Schema
Validation in the MongoDB Server
manual. The default is false . |
| Sets the codec to use for encoding or decoding documents. Bulk writes
use the codec for insertOne() and replaceOne() operations.
For more information, see the Codecs guide. |
| Sets the write concern for the operation.
For more information, see Write Concern
in the MongoDB Server manual. |
| 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. |
| If set to true : When a single write fails, the operation stops without
performing the remaining writes and throws an exception.If set to false : When a single write fails, the operation continues to
attempt the remaining write operations, if any, then throws an exception.The default is true . |
| Attaches a comment to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
| Specifies the client session to associate with the operation. |
The following example calls the bulkWrite()
method to perform an
insert and delete operation and sets the ordered
option to
false
:
$result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ ['name' => 'Mongo\'s Pizza'], ['cuisine' => 'Italian'], ['borough' => 'Queens'], ['restaurant_id' => '5678'], ], ], [ 'deleteOne' => [ ['restaurant_id' => '5678'], ], ], ], ['ordered' => false] );
If the library runs the insert operation first, one document is deleted. If it runs the delete operation first, no documents are deleted.
Note
Unordered Behavior
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 MongoDB\Collection::bulkWrite()
method returns a MongoDB\BulkWriteResult
object. This class contains the following methods:
Method | Description |
---|---|
| Returns the total number of documents inserted by all
insert operations in the bulk write command. |
| Returns a map of _id field values for documents
inserted by all insert operations in the bulk write command. |
| Returns the total number of documents matched by all
update and replace operations in the bulk write command. |
| Returns the total number of documents modified by all update
and replace operations in the bulk write command. |
| Returns the total number of documents upserted by all update
and replace operations in the bulk write command. |
| Returns a map of _id field values for documents
upserted by all update and replace operations in the bulk write
command. |
| Return the total number of documents deleted by all delete
operations in the bulk write command. |
| Returns a boolean indicating whether the server acknowledged
the bulk operation. |
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:
Client Bulk Write
Collection Bulk Write