How To Update A MongoDB Document Using The Golang Driver

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you have data stored in MongoDB, there’s a good chance you’ll need to update certain documents from time to time. Fortunately, the Golang driver for MongoDB makes it quick and easy to accomplish this task. In this article, we’ll show you exactly how to update a MongoDB document with Golang using the mongo-go-driver.

Prerequisites

Before we attempt to update a MongoDB document with Golang, let’s make sure all the prerequisites are in place:

  • You’ll need to make sure MongoDB is running. To check, just type mongo in a terminal window to try to enter the Mongo Shell.

  • Golang needs to be installed on the same machine that’s running MongoDB, and the $GOPATH directory for the Golang projects must be set.

  • The mongo-go-driver Golang driver for MongoDB needs to be installed in the machine’s designated $GOPATH:

1
go get go.mongodb.org/mongo-driver/mongo
  • You’ll need to have at least one document already in a MongoDB collection that you don’t mind updating.

Connect to MongoDB using a Golang script

The API call to MongoDB must take place within a Golang script that uses the .go file extension. Before proceeding, you should create one now in a folder window or use the touch command in a terminal window. Don’t forget to include package main at the top of the script.

Import the required MongoDB and Golang Packages

Next, we’ll use Golang’s import statement at the top of our script to import the different Golang and MongoDB packages we’ll need to update a document:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main

import (

    // Built-in Golang packages
    "context" // manage multiple requests
    "fmt"     // Println() function
    "os"
    "reflect" // get an object type

    // Official 'mongo-go-driver' packages
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {

    // Declare host and port options to pass to the Connect() method
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    fmt.Println("clientOptions TYPE:", reflect.TypeOf(clientOptions), "\n")

    // Connect to the MongoDB and return Client instance
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        fmt.Println("mongo.Connect() ERROR:", err)
        os.Exit(1)
    }

    // Declare Context type object for managing multiple API requests
    //ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
    fmt.Println("context type:", reflect.TypeOf(context.Background()), "\n")

    // Access a MongoDB collection through a database
    col := client.Database("some_database").Collection("Some Collection")
    fmt.Println("Collection type:", reflect.TypeOf(col), "\n")

    // Declare an _id string and create an ObjectID
    docID := "5d1719988f83df290e8c92ca"
    objID, err := primitive.ObjectIDFromHex(docID)

    // Check for MongoDB ID ObjectIDFromHex errors
    if err != nil {
        fmt.Println("ObjectIDFromHex ERROR", err)
    } else {
        fmt.Println("ObjectIDFromHex:", objID)
    }

    // Declare an _id filter to get a specific MongoDB document
    filter := bson.M{"_id": bson.M{"$eq": objID}}

    // Declare a BSON update object that will change a boolean field to 'false'
    /*
        filter := bson.M{
            "fieldbool": bson.M{
                "$eq": false, // check if bool field has value of 'false'
            },
        }
    */


    // Declare a filter that will change a field's integer value to `42`
    update := bson.M{"$set": bson.M{"fieldint": 42}}

    // Call the driver's UpdateOne() method and pass filter and update to it
    result, err := col.UpdateOne(
        context.Background(),
        filter,
        update,
    )

    // Check for error, else print the UpdateOne() API call results
    if err != nil {
        fmt.Println("UpdateOne() result ERROR:", err)
        os.Exit(1)
    } else {
        fmt.Println("UpdateOne() result:", result)
        fmt.Println("UpdateOne() result TYPE:", reflect.TypeOf(result))
        fmt.Println("UpdateOne() result MatchedCount:", result.MatchedCount)
        fmt.Println("UpdateOne() result ModifiedCount:", result.ModifiedCount)
        fmt.Println("UpdateOne() result UpsertedCount:", result.UpsertedCount)
        fmt.Println("UpdateOne() result UpsertedID:", result.UpsertedID)
    }
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.