Replace a Document![](/docs/drivers/go/v1.8/assets/link.svg)
You can replace a document in a collection by using the ReplaceOne()
method.
Example![](/docs/drivers/go/v1.8/assets/link.svg)
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
name
is "Madame Vo"Replaces the matched document with a new document
coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"name", "Madame Vo"}} replacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"} result, err := coll.ReplaceOne(context.TODO(), filter, replacement) if err != nil { panic(err) }
View a fully runnable example
Expected Result![](/docs/drivers/go/v1.8/assets/link.svg)
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![](/docs/drivers/go/v1.8/assets/link.svg)
To learn more about replacing documents, specifying query filters, and handling potential errors, see Modify Documents.