In a previous tutorial, I demonstrated how to connect to a MongoDB cluster with the Go programming language (Golang) and verify the connection through pinging the cluster and outputting the available databases. In this tutorial, we're going to continue with the getting started material, but this time connecting to a particular collection to create new documents. This will continue to use the Go programming language.

Tools and Versions for the Tutorial Series

I wanted to take a moment to reiterate the tools and versions that I'm using within this tutorial series:

  • MongoDB Atlas with an M0 free cluster
  • Visual Studio Code (VSCode)
  • MongoDB Go Driver 1.1.2
  • Go 1.13

If you're using different software or more recent versions, don't worry, the code should be fine, the steps just might be a little different.

The assumption is that you've configured everything prior to using this tutorial in the series.

Understanding the Data

As a refresher, MongoDB stores data in JSON documents, which are actually Binary JSON (BSON) objects stored on disk. We won't get into the nitty gritty of how MongoDB works with JSON and BSON in this particular series, but we will familiarize ourselves with some of the data we'll be working with going forward.

Take the following MongoDB documents for example:

{
    "_id": ObjectId("5d9e0173c1305d2a54eb431a"),
    "title": "The Polyglot Developer Podcast",
    "author": "Nic Raboy"
}
podcasts
{
    "_id": ObjectId("5d9f4701e9948c0f65c9165d"),
    "podcast": ObjectId("5d9e0173c1305d2a54eb431a"),
    "title": "GraphQL for API Development",
    "description": "Learn about GraphQL development in this episode of the podcast.",
    "duration": 25
}
episodes

Getting a Handle to a Specific Collection

Before data can be created or queried, a handle to a collection must be defined. It doesn't matter if the database or collection already exists on the cluster as it will be created automatically when the first document is inserted if it does not.

Since we will be using two different collections, the following can be done in Go to establish the collection handles:

quickstartDatabase := client.Database("quickstart")
podcastsCollection := quickstartDatabase.Collection("podcasts")
episodesCollection := quickstartDatabase.Collection("episodes")
clientquickstartclient

Looking at our code thus far, we might have something that looks like the following:

package main

import (
	"context"
	"log"
	"time"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

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)

    quickstartDatabase := client.Database("quickstart")
    podcastsCollection := quickstartDatabase.Collection("podcasts")
    episodesCollection := quickstartDatabase.Collection("episodes")
}

Between this tutorial and the first tutorial in the series, the cluster ping logic and listing of database logic was removed. Instead, we're just connecting to the cluster and creating handles to our collections in a particular database.

Creating One or Many BSON Documents in a Single Request

podcastsCollectionepisodesCollection

For this example, I won't be using a pre-defined schema. In a future tutorial, we'll see how to map documents to native Go data structures, but for now, we're going to look at other options.

Take the following command for example:

podcastResult, err := podcastsCollection.InsertOne(ctx, bson.D{
    {Key: "title", Value: "The Polyglot Developer Podcast"},
    {Key: "author", Value: "Nic Raboy"},
})
podcasts
podcastResult, err := podcastsCollection.InsertOne(ctx, bson.D{
    {Key: "title", Value: "The Polyglot Developer Podcast"},
    {Key: "author", Value: "Nic Raboy"},
    {Key: "tags", Value: bson.A{"development", "programming", "coding"}},
})
tagsbson.Dbson.A
bson.Dbson.A
podcastResult, err := podcastsCollection.InsertOne(ctx, bson.D{
    {"title", "The Polyglot Developer Podcast"},
    {"author", "Nic Raboy"},
    {"tags", bson.A{"development", "programming", "coding"}},
})
KeyValue
InsertOneInsertOneResultInsertOneResultpodcastResultInsertedID
InsertOneInsertMany
episodeResult, err := episodesCollection.InsertMany(ctx, []interface{}{
    bson.D{
        {"podcast", podcastResult.InsertedID},
        {"title", "GraphQL for API Development"},
        {"description", "Learn about GraphQL from the co-creator of GraphQL, Lee Byron."},
        {"duration", 25},
    },
    bson.D{
        {"podcast", podcastResult.InsertedID},
        {"title", "Progressive Web Application Development"},
        {"description", "Learn about PWA development with Tara Manicsic."},
        {"duration", 32},
    },
})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Inserted %v documents into episode collection!\n", len(episodeResult.InsertedIDs))
interface{}bson.DInsertedID
InsertOneResultInsertManyInsertManyResultInsertedIDs[]interface{}

Conclusion

You just saw how to insert documents into a MongoDB cluster using the Go programming language. In this particular part of the series, primitive data structures were used to save us from having to pre-define a schema. In a future tutorial, we're going to see how to make our projects more manageable by defining how MongoDB documents can be mapped to Go data structures.

With data in the database, the next part of the getting started series will include how to query for the data using Go.

You can see a video of this tutorial in action below.