Bulk Write Operations
On this page
Overview
In this guide, you can learn how to use the Ruby driver to perform a bulk write operation that makes multiple changes to your data in a single database call.
Consider a situation that requires you to insert documents, update documents, and delete documents for the same task. If you use the individual write methods, each write operation accesses the database separately. Instead, you can use a bulk write operation to optimize the number of calls your application makes to the server.
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 Ruby application, create a Mongo::Client
object that connects to an Atlas cluster
and assign the following values to your database
and collection
variables:
database = client.use('sample_restaurants') collection = database[:restaurants]
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
Define the Write Operations
For each write operation you want to perform, create a hash that implements one of the following operations:
insert_one
update_one
update_many
replace_one
delete_one
delete_many
Then, pass a list of these instances to the bulk_write
method.
The following sections show how to create and use instances of the
preceding operations. The Perform the Bulk Operation section
demonstrates how to pass a list of hashes to the bulk_write
method
to perform the bulk operation.
Insert Operations
To perform an insert operation, create an insert_one
hash and specify
the document you want to insert.
The following example creates an insert_one
hash:
insert_one = { insert_one: { name: 'Steve Rogers Cafe', borough: 'Brooklyn' } }
To insert multiple documents, create a separate insert_one
hash
for each document.
Important
When performing a bulk operation, the insert_one
operation cannot
insert a document with an _id
that already exists in the
collection. In this situation, the driver throws a
MongoBulkWriteException
.
Update Operations
To update a document, create an update_one
hash and pass
the following arguments:
Query filter that specifies the criteria used to match documents in your collection.
Update operation you want to perform. For more information about update operations, see the Field Update Operators guide in the MongoDB Server manual.
The update_one
operation specifies an update for the first
document that matches your query filter.
The following example creates an update_one
hash:
update_one = { update_one: { filter: { name: 'Mountain View' }, update: { '$set': { borough: 'Queens' } } } }
To update multiple documents, create an update_many
hash and pass
the same arguments as for an update_one
operation. The update_many
operation specifies updates for all documents that match your query
filter.
The following example creates an update_many
hash:
update_many = { update_many: { filter: { name: 'Starbucks' }, update: { '$set': { cuisine: 'Cafe' } } } }
Replace Operations
A replace operation removes all fields and values of a specified document and
replaces them with new fields and values that you specify. To perform a
replace operation, create a replace_one
hash and pass the following
arguments:
Query filter that specifies the criteria used to match documents in your collection
Replacement document that specifies the new fields and values to insert
The following example creates a replace_one
hash:
replace_one = { replace_one: { filter: { name: 'Old World Diner' }, replacement: { '$set': { name: 'New Age Luncheonette' } } } }
To replace multiple documents, you must create a
replace_one
hash for each document.
Delete Operations
To delete a document, create a delete_one
hash and pass a
query filter specifying the document you want to delete. The
delete_one
operation deletes only the first document that matches your query filter.
The following example creates a delete_one
hash:
delete_one = { delete_one: { name: 'Old World Diner' } }
To delete multiple documents, create a delete_many
hash and pass a
query filter specifying the document you want to delete. The
delete_many
operation deletes all documents that match your query filter.
The following example creates a delete_many
hash:
delete_many = { delete_many: { name: 'Starbucks' } }
Perform the Bulk Operation
After you define a hash for each operation you want to perform,
pass a list of these objects to the bulk_write
method.
By default, the method runs the operations in the order
specified by the list of hashes.
The following example performs multiple write operations by using the
bulk_write
method:
insert_one = { insert_one: { name: 'Nuovo Ristorante', borough: 'Brooklyn', cuisine: 'Italian' } } update_one = { update_one: { filter: { name: 'Moonlit Tavern' }, update: { '$set': { borough: 'Queens' } } } } delete_many = { delete_many: { name: 'Crepe' } } writes = [insert_one, update_one, delete_many] collection.bulk_write(writes)
If any of the write operations fail, the Ruby driver raises a
BulkWriteError
and does not perform any further operations.
BulkWriteError
provides a details
item that includes the
operation that failed and details about the exception.
Note
When the driver 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
The bulk_write
method optionally accepts an options
hash which
specifies options you can use to configure the bulk write
operation. If you don't specify any options, the driver performs the
bulk operation with default settings.
The following table describes the options that you can use to
configure the bulk_write
method:
Option | Description |
---|---|
| 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 . |
| Specifies whether the update operation bypasses document validation. This lets you
update 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. Defaults to false . |
| The session to use for the operation. Type: Session |
| Provides a map of parameter names and values to set top-level
variables for the operation. Values must be constant or closed
expressions that don't reference document fields. |
The following code creates options and sets the ordered
option to false
to
specify an unordered bulk write. Then, the code uses the
bulk_write
method to perform the same bulk operations as the preceding example:
options = { ordered: false } collection.bulk_write(writes, options)
If any of the write operations in an unordered bulk write fail, the Ruby driver reports the errors only after attempting all operations.
Note
Unordered bulk operations do not guarantee an order of execution. The order can differ from the way you list them to optimize the runtime.
Return Value
The bulk_write
method returns a BulkWrite::Result
. You can access information from
the Result
instance by using the following instance methods:
Method | Description |
---|---|
| Indicates if the server acknowledged the write operation. |
| Returns the number of documents deleted, if any. |
| Returns the number of documents inserted, if any. |
| Returns the list of inserted document ids, if any. |
| Returns the number of documents matched for an update, if applicable. |
| Returns the number of documents modified, if any. |
| Returns the number of upserted documents, if any. |
| Returns the list of upserted document ids, if any. |
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: