Quick Start: Golang & MongoDB - Starting and Setup

Nicolas Raboy

Quick Start Go and MongoDB

In the first tutorial, which can best be named a Quick Start into MongoDB development with the Go programming language (Golang), we're going to be exploring how to establish connections between the language and the database.

When it comes to future tutorials in the series, expect content on the following:

  • Database create, retrieve, update, and delete (CRUD) operations.
  • A look into MongoDB aggregation queries.
  • Watching change streams in MongoDB.
  • Multi-Document ACID transactions.

Go is one of the more recent of the officially supported technologies with MongoDB, and in my personal opinion, it is one of the most awesome!

Throughout these tutorials, I'll be using Visual Studio Code (VS Code) for development, and I'll be connecting to a MongoDB Atlas cluster. The assumption is that you're using Go 1.13 or newer and that it is already properly installed and configured on your computer. It is also assumed that an Atlas cluster has already been created.

MongoDB Atlas offers a forever FREE tier that can be accessed within the MongoDB Cloud.

If you're using a different IDE, O/S, etc., the walk-through might be slightly different, but the code will be pretty much the same.

Getting Started

Create a new project directory titled quickstart, and add a main.go file to that project.

For this particular tutorial, all code will be added to the main.go file. We can start the main.go file with the following boilerplate code, necessary for our dependency manager:

package main

func main() { }

The next step is to install the MongoDB Go Driver using Go modules. To do this, execute the following from the command line:

$ go mod init quickstart
$ go get go.mongodb.org/mongo-driver

Note that for this tutorial we are using Go modules to manage our packages. This requires Go version 1.11 or higher. If using Go 1.11, this requires the quickstart module to be created outside $GOPATH/src if you also have a $GOPATH set up. For more information about Go modules, see https://blog.golang.org/using-go-modules.

With the driver installed, open the project's main.go file, and add the following imports to the code:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() { }

The above code represents the imported modules within the MongoDB Go Driver that will be used throughout the tutorial series. Most logic, at least for now, will exist in the main function.

Inside the main function, let's establish a connection to our MongoDB Atlas cluster:

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("<ATLAS_URI_HERE>"))
	if err != nil {
		log.Fatal(err)
	}
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)
}

There are a few things that are happening in the above code. First we're configuring our client to use the correct URI, but we're not yet connecting to it. Assuming nothing is malformed and no error was thrown, we can define a timeout duration that we want to use when trying to connect. The ten seconds I used might be a little too generous for your needs, but feel free to play around with the value that makes the most sense to you.

In regards to the Atlas URI, you can use any of the driver URIs from the Atlas dashboard. They'll look something like this:

mongodb+srv://<username>:<password>@cluster0-zzart.mongodb.net/test?retryWrites=true&w=majority

Just remember to use the information that Atlas provides for your particular cluster.

After connecting, if there isn't an error, we can defer the closing of the connection for when the main function exits. This will keep the connection to the database open until we're done.

So if no errors were thrown, can we be sure that we're really connected? If you're concerned, we can ping the cluster from within our application:

err = client.Ping(ctx, readpref.Primary())
if err != nil {
    log.Fatal(err)
}

The above code uses our connected client and the context that we had previously defined. If there is no error, the ping was a success!

We can take things a step further by listing the available databases on our MongoDB Atlas cluster. Within the main function, add the following:

databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
    log.Fatal(err)
}
fmt.Println(databases)

The above code will return a []string with each of the database names. Since we don't plan to filter any of the databases in the list, the filter argument on the ListDatabaseNames function can be bson.M{}.

The result of the above code might be something like this:

[quickstart video admin local]

Of course, your actual databases will likely be different than mine. It is not a requirement to have specific databases or collections at this stage of the tutorial.

To bring everything together, take a look at our project thus far:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("<ATLAS_URI_HERE>"))
	if err != nil {
		log.Fatal(err)
	}
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		log.Fatal(err)
	}
	databases, err := client.ListDatabaseNames(ctx, bson.M{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(databases)
}

Not bad for 34 lines of code, considering that about half of that was just defining the imports for packages to be used within the project.

Conclusion

You just saw how to connect to a MongoDB Atlas cluster with the Go programming language. If you decide not to use Atlas, the code will still work, you'll just have a different connection string.

Go is a powerful technology and combined with MongoDB you can accomplish anything from web applications to desktop applications.

Stay tuned for the next tutorial in the series which focuses on CRUD operations against MongoDB using Golang.

Take a look at a video of this in action below.