How To Install and Use the Go Driver in MongoDB

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

Introduction

If you’d like to use the popular Go programming language to interact with your MongoDB instance, you may be wondering how to get started. Fortunately, the MongoDB Go driver makes this task a simple one. Installing the driver only takes a moment, and it’s easy to connect Go to MongoDB with just a few lines of code. In this article, we’ll provide step-by-step instructions for connecting the Go language to MongoDB via the Go driver, and we’ll also provide a basic code example that accesses a MongoDB collection and executes a query.

Prerequisites

Before we move forward with installing the driver, let’s go over the system requirements for this task. There are a few prerequisites that need to be in place:

  • First, you need to ensure that MongoDB has been properly installed and configured.

  • You must also ensure that the Go language has been properly installed and configured. To check if Go is installed, run the following command:

1
go version

You should get a result that looks something like the following:

1
go version go1.12.5 linux/amd64

Go displays the currently installed version as well as the OS where it was installed (this may vary).

The MongoDB Dataset

If you’re following along with the code examples in this tutorial, you’ll find it helpful to work with the same set of data. The table below represents the sample dataset that will be used in this tutorial:

IDNameRatingCountry
5ceb7d233fd48a1ebd04318eChang Kai-shek11China
5ceb7d233fd48a1ebd04318fSun Yat-sen8China
5ceb7d233fd48a1ebd043190Muammar al-Gaddafi15Libya
5ceb7d233fd48a1ebd043191Oda Nobunaga15Japan
5ceb7d233fd48a1ebd043192Cao Cao19China
5ceb7d233fd48a1ebd043193Sun Tzu10China

Installing the Go Driver for MongoDB

Installing the Go driver for MongoDB is a simple task– all you need to do is run the command shown below in the terminal:

1
go get go.mongodb.org/mongo-driver

The result you get will look something like this:

1
package go.mongodb.org/mongo-driver: no Go files in /home/usename/go_projects/src/go.mongodb.org/mongo-driver

Connecting Go Driver to MongoDB

Now that we’ve installed the appropriate driver, we can move forward with connecting Go to MongoDB. The code shown below will connect the Go language to a MongoDB deployment and access a database and collection available on that deployment.

In this example, the code simply performs a basic search:

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
package main

import (
"context"
"fmt"
"log"
// importing the required dependencies
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)


// This creates fixed sets of unique fields
type Trainer struct {
Name, Country string
Rating int
}

func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}

// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// Get a handle of the collection
collection := client.Database("warlordDB").Collection("warlordCollection")

// filter to be used for the search query in bson format
filter := bson.D{{"name", "Cao Cao"}}


var result Trainer

// searching a document using FindOne function against the specified filter
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Found a single document: %+v\n", result)
}

Let’s take a closer look at what’s happening in this simple example. First, we access the database "warlordDB" and then access the collection "warlordCollection" available within that database. Then we perform a simple query, looking for documents where the value of "name" is "Cao Cao". A single result is returned.

To test “main.go”, navigate to the project directory, then use the following command:

1
go run main.go

The output should look something like this:

1
2
Connected to MongoDB!
Found a single document: {Name:Cao Cao Country:China Rating:19}

Conclusion

If you’re using MongoDB to store your data, it can be helpful to use a popular programming language like Go to interact with your database and query your data. With the MongoDB Go driver, it’s easy to connect Go with your deployment of MongoDB. Using the instructions provided in this tutorial, you’ll have no trouble connecting the Go language to MongoDB via the Go driver.

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.