Docs Menu

Docs HomeGo

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.

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

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.

To learn more about replacing documents, specifying query filters, and handling potential errors, see Change a Document.

ReplaceOne()

←  Update Multiple DocumentsDelete a Document →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.