Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversGo Driver

Replace a Document

You can replace a document in a collection by using the ReplaceOne() method.

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"}}
// Creates a new document containing "Name" and "Cuisine" fields
replacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"}
// Replaces the first document that matches the filter with a new document
result, err := coll.ReplaceOne(context.TODO(), filter, replacement)
if err != nil {
panic(err)
}

View a fully runnable example

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.

To learn more about replacing documents, specifying query filters, and handling potential errors, see Modify Documents.

ReplaceOne()

←  Update Multiple DocumentsDelete a Document →