Docs Menu
Docs Home
/ / /
Go Driver
/ /

Replace Documents

In this guide, you can learn how to use the Go driver to perform a replace operation on a document in a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. A replace operation removes all fields in the target document and replaces them with new ones.

ReplaceOne() expects a replacement document, which is the document that you want to take the place of an existing document. Replacement documents use the following format:

bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... }

ReplaceOne() returns an UpdateResult type that contains information about the replace operation if the operation is successful. The UpdateResult type contains the following properties:

Property
Description

MatchedCount

The number of documents matched by the filter

ModifiedCount

The number of documents modified by the operation

UpsertedCount

The number of documents upserted by the operation

UpsertedID

The _id of the upserted document, or nil if there is none

If multiple documents match the query filter passed to ReplaceOne(), the method selects and replaces the first matched document. Your replace operation fails if no documents match the query filter.

The following document describes a kitchen item:

{
"_id" : 2056,
"item" : "Mug",
"brand" : "Simply Ceramics",
"price" : 2.99,
"material" : "Glass"
}

The following example uses the ReplaceOne() method to substitute this document with one that contains an item field with a value of "Cup" and a quantity field with a value of 107:

filter := bson.D{{"_id", 2056}}
replacement := bson.D{{"item", "Cup"}, {"quantity", 107}}
result, err := collection.ReplaceOne(context.TODO(), filter, replacement)
fmt.Printf("Documents matched: %v\n", result.MatchedCount)
fmt.Printf("Documents replaced: %v\n", result.ModifiedCount)
Documents matched: 1
Documents replaced: 1

The replaced document contains the contents of the replacement document and the immutable _id field as follows:

{
"_id" : 2056,
"item" : "Cup",
"quantity" : 107
}

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

  • ReplaceOne()

  • UpdateResult

Back

Update Documents

On this page