Docs Menu
Docs Home
/ / /
Go Driver

Go Driver Quick Start

This guide shows you how to create an application that uses the MongoDB Go Driver to connect to a MongoDB Atlas cluster. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official MongoDB drivers.

The Go driver lets you connect to and communicate with MongoDB clusters from a Go application.

MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB clusters. In this guide, we show you how to get started with your own free (no credit card required) cluster.

Follow the steps below to connect your Go application with a MongoDB Atlas cluster.

1

Create a new directory and initialize your project by using go mod, as shown in the following commands:

mkdir go-quickstart
cd go-quickstart
go mod init go-quickstart
2

Use go get to add the Go driver as a dependency, as shown in the following command:

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

You can create a free tier MongoDB deployment on MongoDB Atlas to store and manage your data. MongoDB Altas hosts and manages your MongoDB database in the cloud.

1

Complete the Get Started with Atlas guide to set up a new Atlas account, create a free tier MongoDB cluster, load datasets, and interact with the data.

2

After you create your database user, save that user's username and password to a safe location for use in an upcoming step.

After completing these steps, you have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster.

You can connect to your MongoDB deployment by providing a connection URI, also called a connection string, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.

The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.

1

To retrieve your connection string for the cluster you created in the previous section, do the following:

  1. Log in to your Atlas account.

  2. Navigate to the Database section on the sidebar and select Clusters.

  3. Find the cluster you would like to connect to and click the Connect button.

  4. Under , click the Drivers option.

  5. Select "Go" from the Driver selection menu and the appropriate version from the Version selection menu.

  6. Copy the connection string clipboard, as shown in the following screenshot:

2

Paste this connection string into a file in your preferred text editor and replace the <db_username> and <db_password> placeholders with your database user's username and password.

Save this file to a safe location for use in the next step.

After completing these steps, you have a connection string that corresponds your Atlas cluster.

To learn more about connecting to Atlas through the MongoDB Go Driver and applying connection options, see the Atlas driver connection guide.

1

In your terminal, run the following command to create an environment variable called MONGODB_URI and set your Atlas connection string as its value:

export MONGODB_URI='<your atlas connection string>'

Note

Make sure to replace the <db_password> section of the connection string with the password you created for your user that has atlasAdmin permissions.

2

Run the following command from the base directory of your project to create a new file called main.go:

touch main.go
3

Copy and paste the following code into your main.go file. This code runs a query on your sample dataset in MongoDB Atlas.

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
uri := os.Getenv("MONGODB_URI")
docs := "www.mongodb.com/docs/drivers/go/current/"
if uri == "" {
log.Fatal("Set your 'MONGODB_URI' environment variable. " +
"See: " + docs +
"usage-examples/#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_mflix").Collection("movies")
title := "Back to the Future"
var result bson.M
err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).
Decode(&result)
if err == mongo.ErrNoDocuments {
fmt.Printf("No document was found with the title %s\n", title)
return
}
if err != nil {
panic(err)
}
jsonData, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", jsonData)
}
4

Run the sample code with the following command from your command line:

go run main.go

When you run main.go, it outputs the details of the movie from the sample dataset, which resembles the following:

{
"_id": "573a1398f29313caabce9682",
...
"title": "Back to the Future",
...
}

Tip

If you receive no output or an error, check whether you properly set up your environment variable and ensure you have loaded the sample datasets into your cluster.

After you complete these steps, you have a working application that uses the MongoDB Go Driver to connect to your MongoDB cluster, runs a query on the sample data, and prints out the result.

Learn how to read and modify data using the MongoDB Go Driver in the CRUD Operations section or how to perform common operations from our Usage Examples.

Back

MongoDB Go Driver

On this page

  • Set Up Your Project
  • Create and initialize your project
  • Add the MongoDB Go Driver as a dependency
  • Create a MongoDB Cluster
  • Set up a Free Tier Cluster in Atlas
  • Connect to Your Cluster
  • Query Your MongoDB Cluster from Your Application
  • Add your connection string
  • Create a new file
  • Create your Go application
  • Run your application
  • Next Steps