Docs Menu

Bulk Operations

On this page

  • Overview
  • Sample Data
  • Bulk Write
  • Modify Behavior
  • Return Values
  • Operations
  • Insert
  • Replace
  • Update
  • Delete
  • Execution Order
  • Ordered
  • Unordered
  • Additional Information
  • Related Operations
  • API Documentation

In this guide, you can learn how to use bulk operations.

Bulk operations perform a large number of write operations. Instead of making a call for each operation to the database, bulk operations perform multiple operations with one call to the database.

To run the example in this guide, load the sample data into the tea.ratings collection with the following snippet:

coll := client.Database("tea").Collection("ratings")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"rating", 10}},
bson.D{{"type", "Earl Grey"}, {"rating", 5}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
Non-existent Databases and Collections

If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.

Each document contains a rating for a type of tea that corresponds to the type and rating fields.

Note

Each example truncates the ObjectID value because the driver generates them uniquely.

To perform a bulk operation, pass a slice of WriteModel documents to the BulkWrite() method.

The BulkWrite() method optionally takes a BulkWriteOptions type, which represents options you can use to modify its behavior. If you don't specify a BulkWriteOptions, the driver uses the default values for each option.

The BulkWriteOptions type allows you to configure options with the following methods:

Method
Description
SetBypassDocumentValidation()
Whether to allow the write to opt-out of document level validation.
Default: false
SetOrdered()
Whether to stop performing write operations after an error occurs.
Default: true

The BulkWrite() method returns a BulkWriteResult type, which contains information about the bulk operation if it's successful. The BulkWriteResult type contains the following properties:

Property
Description
InsertedCount
The number of documents inserted.
MatchedCount
The number of documents matched by the query filter in update and replace operations.
ModifiedCount
The number of documents modified by update and replace operations.
DeletedCount
The number of documents deleted.
UpsertedCount
The number of documents upserted by update and replace operations.
UpsertedIDs
A map of an operation index to the _id of each upserted document.

A WriteModel represents an insert, replace, update, or delete operation.

To perform an insert operation, create an InsertOneModel specifying the document you want to insert. To insert multiple documents, create an InsertOneModel for each document you want to insert.

The InsertOneModel allows you to specify its behavior with the following method:

Method
Description
SetDocument()
The document to insert.

This following example creates two InsertOneModel instances to insert two documents:

models := []mongo.WriteModel{
mongo.NewInsertOneModel().SetDocument(bson.D{{"type", "Oolong"}, {"rating", 9}}),
mongo.NewInsertOneModel().SetDocument(bson.D{{"type", "Assam"}, {"rating", 6}}),
}

To perform a replace operation, create a ReplaceOneModel specifying the document you want to replace and a replacement document. To replace multiple documents, create a ReplaceOneModel for each document you want to replace.

The ReplaceOneModel allows you to specify its behavior with the following methods:

Method
Description
SetCollation()
The type of language collation to use when sorting results.
SetFilter()
The query filter specifying which document to replace.
SetHint()
The index to use to scan for documents.
SetReplacement()
The document to replace the matched document with.
SetUpsert()
Whether to insert a new document if the query filter doesn't match any documents.

The following example creates a ReplaceOneModel to replace a document where the type is "Earl Grey" with a document where the type is "Matcha" and the rating is 8:

models := []mongo.WriteModel{
mongo.NewReplaceOneModel().SetFilter(bson.D{{"type", "Earl Grey"}}).
SetReplacement(bson.D{{"type", "Matcha"}, {"rating", 8}}),
}

To perform an update operation, create an UpdateOneModel specifying the document you want to update and an update document. To update multiple documents, use the UpdateManyModel.

The UpdateOneModel and UpdateManyModel allow you to specify their behavior with the following methods:

Method
Description
SetArrayFilters()
The array elements the update applies to.
SetCollation()
The type of language collation to use when sorting results.
SetFilter()
The query filter specifying which document to update.
SetHint()
The index to use to scan for documents.
SetUpdate()
The modifications to apply on the matched documents.
SetUpsert()
Whether to insert a new document if the query filter doesn't match any documents.

The following example creates an UpdateOneModel to decrement a documents rating by 2 if their type is "Masala":

models := []mongo.WriteModel{
mongo.NewUpdateOneModel().SetFilter(bson.D{{"type", "Masala"}}).
SetUpdate(bson.D{{"$inc", bson.D{{"rating", -2}}}}),
}

To perform a delete operation, create a DeleteOneModel specifying the document you want to delete. To delete multiple documents, use the DeleteManyModel.

The DeleteOneModel and DeleteManyModel allow you to specify their behavior with the following methods:

Method
Description
SetCollation()
The type of language collation to use when sorting results.
SetFilter()
The query filter specifying which document to delete.
SetHint()
The index to use to scan for documents.

The following example creates a DeleteManyModel to delete documents where the rating is greater than 7:

models := []mongo.WriteModel{
mongo.NewDeleteManyModel().SetFilter(bson.D{{"rating", bson.D{{"$gt", 7}}}}),
}

The BulkWrite() method allows you to specify if you want to execute the bulk operations as ordered or unordered in its BulkWriteOptions.

By default, the BulkWrite() method executes bulk operations in order you added them and stops if an error occurs.

Tip

This is equivalent to specifying true in the SetOrdered() method:

opts := options.BulkWrite().SetOrdered(true)

To execute bulk write operations in any order and continue if an error occurs, specify false to the SetOrdered() method. The method reports the errors afterwards.

The following example performs the following actions in any order:

  • Inserts two documents.
  • Replaces a document where the type is "Earl Grey" with a new document.
  • Increments all documents rating by 3 if their current rating is less than 7.
  • Deletes all documents where the rating is 9.
models := []mongo.WriteModel{
mongo.NewInsertOneModel().SetDocument(bson.D{{"type", "Oolong"}, {"rating", 9}}),
mongo.NewInsertOneModel().SetDocument(bson.D{{"type", "Assam"}, {"rating", 6}}),
mongo.NewReplaceOneModel().SetFilter(bson.D{{"type", "Earl Grey"}}).
SetReplacement(bson.D{{"type", "Matcha"}, {"rating", 4}}),
mongo.NewUpdateManyModel().SetFilter(bson.D{{"rating", bson.D{{"$lt", 7}}}}).
SetUpdate(bson.D{{"$inc", bson.D{{"rating", 3}}}}),
mongo.NewDeleteManyModel().SetFilter(bson.D{{"rating", 9}}),
}
opts := options.BulkWrite().SetOrdered(false)
results, err := coll.BulkWrite(context.TODO(), models, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", results.InsertedCount)
fmt.Printf("Number of documents replaced or updated: %d\n", results.ModifiedCount)
fmt.Printf("Number of documents deleted: %d\n", results.DeletedCount)

The following documents are present in the ratings collection after the bulk operation:

[{_id ObjectID("...")} {type Masala} {rating 10}]
[{_id ObjectID("...")} {type Matcha} {rating 7}]

For a runnable example on performing a bulk operation, see Perform Bulk Operations.

To learn more about performing the operations mentioned, see the following guides:

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

←  Insert or Update in a Single OperationCompound Operations →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.