Docs Menu

Perform Bulk Operations

You can perform bulk write operations on a collection by using the BulkWrite() method.

Tip

Read the Usage Examples to learn how to run this example.

The following example performs the following in order on the haikus collection:

  • Matches a document in which the title is "Record of a Shriveled Datum" and replace it with a new document
  • Matches a document in which the title is "Dodging Greys" and updates that value to "Dodge The Greys"
coll := client.Database("insertDB").Collection("haikus")
models := []mongo.WriteModel{
mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "Record of a Shriveled Datum"}}).
SetReplacement(bson.D{{"title", "Dodging Greys"}, {"text", "When there're no matches, no longer need to panic. You can use upsert"}}),
mongo.NewUpdateOneModel().SetFilter(bson.D{{"title", "Dodging Greys"}}).
SetUpdate(bson.D{{"$set", bson.D{{"title", "Dodge The Greys"}}}}),
}
opts := options.BulkWrite().SetOrdered(true)
results, err := coll.BulkWrite(context.TODO(), models, opts)

View a fully runnable example

After you run the full example, you can find the following document in the haikus collection:

{
"_id" : ObjectId("..."),
"title" : "Dodge The Greys",
"text" : "When there're no matches, no longer need to panic. You can use upsert."
}

For an example on how to find a document, see Find a Document.

To learn more about performing bulk write operations on a collection and handling potential errors, see Bulk Operations.

←  Delete Multiple DocumentsWatch for Changes →
Give Feedback
© 2022 MongoDB, Inc.

About

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