What Is Golang?

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 makes Go with MongoDB 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 for you.

Benefits of Golang

  1. Go is powerful: its rich language, which feels like a dynamically typed interpreted language, is compiled to static machine code. The code runs natively on different operating systems and hardware specs.
  2. Go is easy to write while its multi core concurrency helps us get the most out of our hardware. It's flexible, expressive, and modular. Because it’s statically compiled to machine code, its run-time power is increased.

MongoDB allows you to work with an on-premises MongoDB installation or cloud-first with MongoDB Atlas. MongoDB’s flexibility makes it an ideal pairing with Go for building services and data processing pipelines alike.

Does MongoDB Support Golang?

Yes, with our MongoDB Go Driver. The MongoDB Go driver and client gives you a number of ways to interact with BSON (Binary JSON) 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, offering types similar to the Go primitives, for BSON 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 field-value pair elements. Finally, A is for arrays of interface{} values.

How Does Golang Connect to MongoDB?

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/mongo

Here’s a code example for connecting to MongoDB in Go:

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

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

func main() {

    /*
            Connect to my cluster
    */
    client, err := mongo.NewClient(options.Client().ApplyURI("<MONGODB_URI>"))
    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)
    
      /*
            List databases
    */
    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(databases)

}

Golang and Atlas

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

If you’re using MongoDB Atlas, make sure that you’ve included your development IP address in the access list and find the connection string in the Atlas console. Once you’re connected, the MongoDB Go Driver has everything you need to query, modify, and work with single documents or multiple documents in your Go application.

When 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.
  • For data science, Tools like Gopher Data, Gopher Notes, and Gota or qframe open up Golang to data.
  • For Machine Learning use cases, you should check out GoLearn.

Golang and MongoDB Example

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 documents in Go is similar to working with JSON or XML.

Here is a code example that shows how to insert and query a set of documents.

/*
         Define my document struct
*/          
type Post struct {
                Title   string   `bson:"title,omitempty"`
                 Body    string   `bson:"body,omitempty"`
           }

/*
         Get my collection instance
*/
    collection := client.Database("blog").Collection("posts")

/*
          Insert documents
*/
    docs := []interface{}{
            bson.D{{"title" , "World"},{"body" , "Hello World"}},
            bson.D{{"title" , "Mars"},{"body" , "Hello Mars"}},
            bson.D{{"title" , "Pluto" }, {"body" , "Hello Pluto"}},
        }

    res, insertErr := collection.InsertMany(ctx, docs)
    if insertErr != nil {
            log.Fatal(insertErr)
    }
      fmt.Println(res);
/*
        Iterate a cursor and print it
*/
    cur, currErr := collection.Find(ctx, bson.D{})

    if currErr != nil { panic(currErr) }
    defer cur.Close(ctx)

    var posts []Post
    if err = cur.All(ctx, &posts); err != nil {
          panic(err)
    }
    fmt.Println(posts)
Ready to try for yourself?

Please see the following tutorial for more information and full code examples: