You can replace a document in a collection by using the ReplaceOne() 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.
This example performs the following actions on the restaurants collection:
Matches a document in which the
nameis "Madame Vo"Replaces the matched document with a new document
coll := client.Database("sample_restaurants").Collection("restaurants")filter := bson.D{{"name", "Madame Vo"}}
// Creates a new document containing "Name" and "Cuisine" fieldsreplacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"}
// Replaces the first document that matches the filter with a new documentresult, err := coll.ReplaceOne(context.TODO(), filter, replacement)if err != nil { panic(err)}View a fully runnable example
Expected Result
After you run the full example, you can find the following replaced document in the restaurants collection:
{ "_id" : ObjectId("..."), "name" : "Monsieur Vo", "cuisine" : "Asian Fusion"}For an example on how to find a document, see the Find a Document usage example.
Additional Information
To learn more about replacing documents, specifying query filters, and handling potential errors, see Modify Documents.