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
}

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the restaurants collection in the sample_restaurants database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

This example performs the following actions on the restaurants collection:

  • Matches a document in which the value of name is "Rizzo's Fine Pizza"

  • Replaces the matched document with a new document

// Replaces the first document that matches a filter by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
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"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"name", "Rizzo's Fine Pizza"}}
// Creates a new document containing "Name" and "Cuisine" fields
replacement := Restaurant{Name: "Rizzo's Pizza", Cuisine: "Pizza/American"}
// 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)
}
// Prints the number of modified documents
if result.MatchedCount != 0 {
fmt.Println("Number of documents replaced:", result.ModifiedCount)
}
// When you run this file for the first time, it should print:
// Number of documents replaced: 1
}
Number of documents replaced: 1

After you run the full example, you can find the following replaced document in the restaurants collection:

{
"_id" : ObjectId("..."),
"name" : "Rizzo's Pizza",
"cuisine" : "Pizza/American"
}

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

Back

Update Documents

On this page