How to use Go with MongoDB on Mac

7.7K views
6 min read

MongoDB is a document-oriented NoSQL database. If you want to use it in your Golang projects, good news — MongoDB does support Golang! Follow this tutorial on connecting Go and MongoDB and developing projects involving both.

In the below article, we describe exactly how to set up your MongoBD as a datasource in Go. Plus, we show how to run some of the basic CRUD operations in the database.

To follow the steps of this Golang — MongoDB tutorial, you’ll need Go installed on your Mac, so make sure you have it before we begin.

Installing the Go driver for MongoDB

In order to use MongoDB with Go, you need a respective driver. Luckily, MongoDB provides official documentation for the process. Let’s go through all the steps together.

Disclaimer: In this post, we are only covering the Go driver, for other MongoDB drivers, check the official documentation.

To get started with MongoDB in Go, initialize your project with go mod in a new directory. Here are the terminal commands for that:

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

Next, add MongoDB dependency with go get command:

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

Now you are ready to create a database cluster in your MongoDB account. To do that, you’ll need to join MongoDB Atlas. It’s a great solution for getting your feet wet with MongoDB in Golang since it has a free tier and is hosted in the cloud.

What you need to do to connect your MongoDB Golang driver is create an Atlas account (you can just sign in through your Google account), deploy a free cluster, add your IP to the allowed connections list, create a database user for the cluster you’ve deployed, connect to the cluster, and begin working with your data.

cloud.mongodb.com database deployment

Go through these steps starting with the registration at https://account.mongodb.com/account/register. If you encounter any hiccups, here’s an official guide to each of the steps.

None of these require code and you should be able to complete the actions in the Atlas interface. Once you complete this step, we can continue with our setup for connecting to your MongoDB database cluster with the help of the MongoDB Go Driver.

Note that when you are connecting to your cluster, you need to select Connect to your application, and then on the next page, copy the connection string to add to your application code:

Connect to Cluster0

Copy your snippet to use later in your code editor. We like to save our code bits in SnippetsLab, a dedicated app to host a library of your code snippets.

mongodb connection snippet in SnippetsLab

Remember to replace and in the snippet with your database password that you’ve created at registration in Atlas. We recommend saving your login credentials in a safe location.

We used app Secrets to save our MongoDB cluster login credentials:

save MongoDB cluster login credentials

Now, create and save the file containing your application into your go-quickstart folder (you can use a different name for your project folder, but make sure you make respective changes in the code we provided in the earlier steps).

We are developing this project in CodeRunner, an app that allows you to save, edit, and run your code in more than 25 languages, including Go. So to write our program, we created the main.go in CodeRunner using MongoDB’s sample code from this official tutorial and put the file in our root folder for the project /go-quickstart.

MongoDB’s sample code

Here’s the code we used:

package main
import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"
    "github.com/joho/godotenv"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
    if err := godotenv.Load(); err != nil {
        log.Println("No .env file found")
    }
    uri := os.Getenv("MONGODB_URI")
    if uri == "" {
        log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
    }
    client, err := mongo.Connect(context.TODO(), 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)
}

Now, in order to successfully run this code, you also need an .env file in your app’s root folder (/go-quickstart in our example).

To create an empty .env file, we used this Terminal command:

touch .env

Next, we added our connection string into the .env file with a series of Terminal commands:

  1. Execute vim .env in Terminal.
  2. Set the value for MONGODB_URI with:
    MONGODB_URI="mongodb+srv://<username>:<password>@cluster0.icb48.mongodb.net/myFirstDatabase?retryWrites=true&w=majority</password></username>
  3. Execute :wq! command.
  4. Execute cat .env in Terminal to check your changes have been saved correctly. Your .env file should read:
    MONGODB_URI="mongodb+srv://<username>:<password>@cluster0.icb48.mongodb.net/myFirstDatabase?retryWrites=true&w=majority</password></username>

Now you are ready to do your MongoDB database ping with command:

go run main.go

If you’ve loaded your sample database as directed in the steps to your Atlas account setup, you should get a response containing information from that sample database.

In our example, we got info from our MongoDB library on a Hollywood movie:

info from our MongoDB library on a Hollywood movie

MongoDB CRUD operations

To perform CRUD operations in MongoDB, you need to import the BSON package. Since its import is included in the code we’ve used for our Go program sample above (from the MongoDB official tutorial), you don’t have to do it manually.

But if you are writing your own thing, the line for import is:

"go.mongodb.org/mongo-driver/bson"

Now, let’s read some data in your sample MongoBD database.

Read a document in MongoDB

Here’s the code you need to add to main.go to make a request for information about The Room movie:

coll := client.Database("sample_mflix").Collection("movies")
var result bson.M
err = coll.FindOne(context.TODO(), bson.D{{"title", "The Room"}}).Decode(&result)
if err != nil {
    if err == mongo.ErrNoDocuments {
        // This error means your query did not match any documents.
        return
    }
    panic(err)
}

You can also copy the full code for your sample main.go file in the official MongoDB tutorial here.

Next, let’s move to writing operations.

Create a document in MongoDB

Add a document to your collection with this code:

coll := client.Database("insertDB").Collection("movies")
doc := bson.D{{"title", "Sunny Days and Nights in 1672"}, {"text", "This is just a test"}}
result, err := coll.InsertOne(context.TODO(), doc)
if err != nil {
    panic(err)
}

Full sample code available in the official MongoDB tutorial on this page.

Run your code and get a confirmation your document has been inserted:

MongoDB main.go

To check, run the find query. You should get your sample info back:

Check your document in MongoDB database

Update a document in MongoDB

Now, you can introduce changes to your database record. To do that, use the update tool.

Here’s a sample code for that:

coll := client.Database("insertDB").Collection("movies")
id, _ := primitive.ObjectIDFromHex("6205210bc9748a7cee6af8cb")
filter := bson.D{{"_id", id}}
update := bson.D{{"$set", bson.D{{"average_rtng", 4.5}}}}
result, err := coll.UpdateOne(context.TODO(), filter, update)
if err != nil {
    panic(err)
}

Your result after running your updated program code should read: Documents updated: 1

Run a find query to test it. Here is what your results can look like (note that we ran quite a few updates to recheck the code, so our results contain a bit more info than with just the above update):

update your document on MongoDB database

Delete a document in MongoDB

And finally, let’s see how we can delete documents from our MongoDB database.

This code will delete the first matched title in your collection:

coll := client.Database("insertDB").Collection("movies")
filter := bson.D{{"title", "Your Newly Updated Title"}}
result, err := coll.DeleteOne(context.TODO(), filter)
if err != nil {
    panic(err)
}

delete documents from our MongoDB database

Conclusion

As you can see, setting up your MongoDB database to work with Golang only takes a few lines of code. We hope this tutorial was helpful in your journey to mastering Golang and MongoDB databases. Go and MongoDB work great together and can be your handy helpers in numerous projects, so we expect you’ve been able to figure out how to use MongoDB with the help of this guide.

Note that MongoDB Atlas only allows you to create one free cluster, and you’ll have to pay for any additional ones.

For our project, we also used three additional apps — CodeRunner, SnippetsLab, and Secrets. You can find them all in Setapp, a curated innovative service of tools for daily productivity and automating routine tasks.

Discover tools for coding, cleaning up your Mac, backing up files, and more on Setapp. Begin with a 7-day free trial right now and try CodeRunner, SnippetsLab, Secrets, and dozens more tools right away.

250+ apps for $9.99
per month

Sign up to Setapp and try them for free.

Security-tested