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.
This example uses the following Restaurant
struct as a model for documents
in the restaurants
collection:
type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address interface{} `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []interface{} `bson:"grades,omitempty"` }
The omitempty
struct tag omits the corresponding
field from the inserted document when left empty.
The following example performs the following in order on the restaurants
collection:
Matches a document in which the
name
is "Cafe Tomato" and replaces it with a new documentMatches a document in which the
name
is "Cafe Zucchini" and updates the value to "Zucchini Land"
coll := client.Database("sample_restaurants").Collection("restaurants") // Creates write models that specify replace and update operations models := []mongo.WriteModel{ mongo.NewReplaceOneModel().SetFilter(bson.D{{"name", "Cafe Tomato"}}). SetReplacement(Restaurant{Name: "Cafe Zucchini", Cuisine: "French"}), mongo.NewUpdateOneModel().SetFilter(bson.D{{"name", "Cafe Zucchini"}}). SetUpdate(bson.D{{"$set", bson.D{{"name", "Zucchini Land"}}}}), } // Specifies that the bulk write is ordered opts := options.BulkWrite().SetOrdered(true) // Runs a bulk write operation for the specified write operations 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 restaurants
collection:
{ "_id": ObjectId("..."), "name": "Zucchini Land", "cuisine": "French" }
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.