Golang and MongoDB

Go is one of the newest languages to get an official MongoDB driver, and the combination of Go’s compiled performance and lightweight, data-friendly syntax make MongoDB and Go a fantastic match for building data-driven applications. If you’re looking to create a high-performance native application, but don’t relish the idea of compiling and running C or C++, Go is just what you’re looking for - and MongoDB’s flexibility makes it an ideal pairing for building services and data processing pipelines alike.

Using MongoDB with Golang

The MongoDB Golang driver gives you a number of ways to interact with BSON data. The most idiomatic is to use structs, similarly to how JSON or XML is mapped and manipulated in Go, but you can also access documents as more open-ended maps for traversal or exploration.

The driver provides the primitives module, providing types similar to the Go primitives, but for BSON (Binary JSON) types that do not otherwise have equivalent Go native types. The M type represents a map with string keys and empty interface{} elements, so that it can hold variable types, the default type of all BSON objects. Because key order matters in some cases (like in query or command documents), the D type simulates a BSON map that maintains key order. D objects are actually just arrays of ordered E structs, which represent individual key-value pair elements. Finally, A is for (obviously) arrays of interface{} values.

Today, you can start cloud-native by setting up a free MongoDB Atlas account rather than (or in addition to) installing MongoDB locally, which will save you time down the road when it comes to sharing your database with other developers or exposing online functionality. Atlas has a perpetual free tier for small databases, and has reasonable consumption-based pricing for more advanced configurations.

How to Setup Golang and MongoDB

Obviously, you’ll need to have Golang installed on your system, and either have MongoDB installed locally, or use MongoDB Atlas to start cloud-first. Next, install the standard MongoDB driver for Golang (for more info on installing Go modules, check out https://blog.golang.org/using-go-modules):

go get go.mongodb.org/mongo-driver

Here’s an example of connecting to MongoDB in Go:

package main

import (


func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI(“<<MongoDB Connection URI>>))
    if err != nil {
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)
    if err != nil {
    defer client.Disconnect(ctx)

If you’re using MongoDB Atlas, make sure that you’ve white-listed your development IP address, and find the connection string in the Atlas console. Once you’re connected, the MongoDB Golang driver has everything you need to query, modify, and work with document data in your Go application.

What You Need to Know

The Go driver supports all of the newest features of MongoDB, including multi-document transactions, client-side encryption, bulk operations, and aggregation for advanced analytics cases. Working with MongoDB document data in Go is similar to working with JSON or XML.

The standard way to work with document data is to use a struct:

type Post struct {

Title string `json:”title,omitempty”`

Body string `json:”body,omitempty”`


You can easily save these structs into MongoDB collections, and map retrieved documents back to the same. Let’s take a look at how to do each.

First, a function that inserts a post:

func InsertPost(title string, body string) {

post := Post{title, body}

collection := client.Database(“my_database”).Collection(“posts”)

insertResult, err := collection.InsertOne(context.TODO(), post)

if err != nil {



fmt.Println(“Inserted post with ID:”, insertResult.InsertedID)


Second, here’s a function that retrieves a post:

func GetPost(id bson.ObjectId) {

collection := client.Database(“my_database”).Collection(“posts”)

filter := bson.D

var post Post

err := collection.FindOne(context.TODO(), filter).Decode(&post)

if err != nil {



fmt.Println(“Found post with title “, post.Title)


How to Use MongoDB with Golang

The MongoDB Go Driver lets you integrate MongoDB into any application, and tap into the impressive Go ecosystem.

There are numerous ways to create applications in Go to leverage MongoDB. For server development, there are full-featured web frameworks like Revel and Gin, lightweight tools like Web.go, and even ultra-simple modular approaches like the Gorilla web toolkit. Tools like Gopher Data, Gopher Notes, and Gota or qframe open up Golang to data science use cases, and people interested in Machine Learning use cases should check out GoLearn.

Ready to get started?

Try MongoDB in the cloud for free with MongoDB Atlas. No credit card required.