Update a Document
You can update a document in a collection by using the UpdateOne()
method.
Example
Tip
Read the Usage Examples to learn how to run this example.
The following example performs the following on the restaurants
collection:
Matches a document with a specific
_id
Creates a new field in the matched document called
avg_rating
with a value of 4.4
coll := client.Database("sample_restaurants").Collection("restaurants") id, _ := primitive.ObjectIDFromHex("5eb3d668b31de5d588f42a7a") filter := bson.D{{"_id", id}} update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}} result, err := coll.UpdateOne(context.TODO(), filter, update) if err != nil { panic(err) }
View a fully runnable example.
Expected Result
After you run the full example, you can find the following updated
document in the restaurants
collection:
// result truncated { "_id" : ObjectId("5eb3d668b31de5d588f42a7a"), ... "name" : "Green House Cafe", "restaurant_id" : "40372112", "avg_rating" : 4.4 }
For an example on how to find a document, see Find a Document.
Additional Information
To learn more about replacing documents, specifying query filters, and handling potential errors, see Change a Document.
To learn more about update operators, see the MongoDB update operator reference documentation.