Docs Menu
Docs Home
/ / /
Go Driver
/

Update Documents

In this guide, you can learn how to update documents in MongoDB by using update operations.

Update operations change the fields that you specify while leaving other fields and values unchanged.

In MongoDB, all methods to modify documents follow the same pattern:

Change method signature

Note

Placeholder

changeX is a placeholder and not a real method.

The pattern expects you to:

  • Specify a query filter to match one or more documents to modify.

  • Specify the field and value changes.

  • Specify options, if you must modify the method behavior.

The driver provides the following methods to update documents:

  • UpdateByID(): Updates a single document based on its _id.

  • UpdateOne(): Updates a single document.

  • UpdateMany(): Updates multiple documents.

Each document in a MongoDB collection has a unique and immutable _id field. You cannot use update operations to change the _id field. If you attempt to change this field, the update methods return a WriteError.

Each method takes an update document that includes at least one update operator. The update operator specifies the type of update to perform. The update document also includes the fields and values that describe the change. Update documents use the following format:

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

See the MongoDB server manual for a complete list of update operators and descriptions.

Tip

UpdateOne() updates the first document that matches the query filter you provide. To ensure that you update the correct document, you can use the sort option to specify the order in which the operation finds documents. To learn more, see the UpdateOneOptions API documentation.

Note

Aggregation Pipelines in Update Operations

You can use aggregation pipelines made up of a subset of aggregation stages in update operations. To learn more about the aggregation stages MongoDB supports in aggregation pipelines, see the tutorial on performing Updates with Aggregation Pipeline tutorial in the Server Manual.

UpdateOne(), UpdateByID(), and UpdateMany() return an UpdateResult type that contains information about the update 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 UpdateOne(), the method selects and updates the first matched document. If no documents match the query filter, the update operation makes no changes.

See the upsert guide to learn how to insert a new document if no documents match the query filter.

The following example uses the listingsAndReviews collection in the sample_airbnb dataset from the Atlas sample datasets. The following document describes an airbnb listing:

{
"_id": "10006546",
"listing_url": "https://www.airbnb.com/rooms/10006546",
"name": "Ribeira Charming Duplex",
"summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...",
...
"minimum_nights": "2",
"maximum_nights": "30",
...
"accommodates": 8,
...
}

The following example uses the UpdateOne() method to:

  • Match the document where the _id value is "10006546".

  • Set the name field to "Ribiera River View Duplex".

  • Increment the value of the accommodates field by 1.

filter := bson.D{{"_id", "10006546"}}
update := bson.D{{"$set", bson.D{{"name", "Ribiera River View Duplex"}}},
{"$inc", bson.D{{"accomodates", 1}}}}
result, err := collection.UpdateOne(context.TODO(), filter, update)
fmt.Printf("Documents matched: %v\n", result.MatchedCount)
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
Documents matched: 1
Documents updated: 1

The following shows the updated document resulting from the preceding update operation:

{
"_id": "10006546",
"listing_url": "https://www.airbnb.com/rooms/10006546",
"name": "Ribeira River View Duplex",
"summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...",
...
"minimum_nights": "2",
"maximum_nights": "30",
...
"accommodates": 9,
...
}

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.

The following example is a fully runnable file that finds and updates an existing document in the restaurants collection. Select the Struct or bson.D tab to see the corresponding code:

The following code uses a struct to define the filter and update a document in the restuarants collection:

// Updates the first document that matches a query 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"
)
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string `bson:"name"`
AverageRating float64 `bson:"avg_rating,omitempty"`
}
// Create a filter struct to specify the document to update
type UpdateRestaurantFilter struct {
ID bson.ObjectID `bson:"_id"`
}
// Defines a RestaurantUpdate struct to specify the fields to update
type RestaurantUpdate struct {
AverageRating float64 `bson:"avg_rating"`
}
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")
id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f4292b")
filter := UpdateRestaurantFilter{ID: id}
// Creates instructions to add the "avg_rating" field to documents
update := bson.D{{"$set", RestaurantUpdate{AverageRating: 4.4}}}
// Updates the first document that has the specified "_id" value
result, err := coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
panic(err)
}
// Prints the number of updated documents
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
}
Documents updated: 1

The following code uses a bson.D type to define the filter and update a document in the restuarants collection:

// Updates the first document that matches a query 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"
)
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")
id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f42a7a")
filter := bson.D{{"_id", id}}
// Creates instructions to add the "avg_rating" field to documents
update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}}
// Updates the first document that has the specified "_id" value
result, err := coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
panic(err)
}
// Prints the number of updated documents
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
}
Documents updated: 1

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.

The following example is a fully runnable file that finds and updates multiple exisiting documents in the restaurants collection. Select the Struct or bson.D tab to see the corresponding code:

The following code uses a struct to define the filter and update multiple documents in the restuarants collection:

// Updates documents that match a query 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"
)
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string `bson:"name"`
Cuisine string `bson:"cuisine"`
AverageRating float64 `bson:"avg_rating,omitempty"`
}
// Create a filter struct to specify the documents to update
type UpdateManyRestaurantFilter struct {
Cuisine string `bson:"cuisine"`
Borough string `bson:"borough"`
}
// Defines a RestaurantUpdate struct to specify the fields to update
type RestaurantUpdateMany struct {
AverageRating float64 `bson:"avg_rating"`
}
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 := UpdateManyRestaurantFilter{
Cuisine: "Pizza",
Borough: "Brooklyn",
}
// Creates instructions to update the values of the "AverageRating" field
update := bson.D{{"$set", RestaurantUpdateMany{AverageRating: 4.5}}}
// Updates documents in which the value of the "Cuisine"
// field is "Pizza"
result, err := coll.UpdateMany(context.TODO(), filter, update)
if err != nil {
panic(err)
}
// Prints the number of updated documents
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
}
Documents updated: 296

The following code uses a bson.D type to define the filter and update multiple documents in the restuarants collection:

// Updates documents that match a query 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"
)
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{{"cuisine", "Pizza"}, {"borough", "Brooklyn"}}
// Creates instructions to update the values of the "avg_rating" field
update := bson.D{{"$set", bson.D{{"avg_rating", 4.5}}}}
// Updates documents in which the value of the "cuisine" field is "Pizza"
// and the value of the "borough" field is "Brooklyn"
result, err := coll.UpdateMany(context.TODO(), filter, update)
if err != nil {
panic(err)
}
// Prints the number of updated documents
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
}
Documents updated: 296

To learn more about the operations mentioned, see the following guides:

To learn more about updating array elements, see Update Arrays in a Document.

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

Back

Geospatial Queries

On this page