Replace a Document
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.
The following example performs the following on the haikus
collection:
Matches a document in which the
title
is "Record of a Shriveled Datum"Replaces the matched document with a new document
coll := client.Database("insertDB").Collection("haikus") filter := bson.D{{"title", "Record of a Shriveled Datum"}} replacement := bson.D{{"title", "Dodging Greys"}, {"text", "When there're no matches, no longer need to panic. You can use upsert"}} result, 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 haikus
collection:
{ "_id" : ObjectId("..."), "title" : "Dodging Greys", "text" : "When there're no matches, no longer need to panic. You can use upsert." }
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.