Perform Bulk Operations
You can perform bulk write operations on a collection by using the
BulkWrite()
method.
Example
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 documentMatches 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
Expected Result
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.
Additional Information
To learn more about performing bulk write operations on a collection and handling potential errors, see Bulk Operations.