MongoDB
suggest changeMongoDB is a document database: it stores BSON documents (binary JSON) in collections instead of rows in tables. The official Go driver is go.mongodb.org/mongo-driver/v2.
Add it to your module:
go get go.mongodb.org/mongo-driver/v2/mongo
Version 2 of the driver changed import paths and several APIs compared to v1 (go.mongodb.org/mongo-driver/mongo). Examples on the web written for v1 won't compile against v2; the differences are listed at the end.
To follow along, run a local server with Docker. Transactions require a replica set, so we start a single-node one:
docker run -d --name mongo -p 27017:27017 mongo:8 --replSet rs0
docker exec mongo mongosh --quiet --eval "rs.initiate()"
All examples below use this Book type and the bookstore database.
Connecting
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)
func main() {
uri := "mongodb://localhost:27017/?replicaSet=rs0&directConnection=true"
client, err := mongo.Connect(options.Client().
ApplyURI(uri).
SetTimeout(10 * time.Second))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.Fatal(err)
}
}()
// Connect doesn't talk to the server; Ping verifies it's reachable.
if err := client.Ping(ctx, readpref.Primary()); err != nil {
log.Fatal(err)
}
fmt.Println("connected")
coll := client.Database("bookstore").Collection("books")
_ = coll
}
connected
A few things to know:
mongo.Connectdoesn't take a context in v2. It only validates options and starts background connection monitoring, so it succeeds even if the server is down. UsePingto fail fast at startup.*mongo.Clientis safe for concurrent use and maintains a connection pool. Create one per process and share it (for example by passing it to constructors, see Dependency injection). Don't connect per request.SetTimeoutsets a default timeout for every operation. You can still pass a context with a deadline to individual calls.DatabaseandCollectionare cheap, they don't contact the server. Databases and collections are created on first insert.
Mapping structs to documents
The driver encodes Go structs to BSON using bson struct tags, similar to encoding/json:
type Book struct {
ID bson.ObjectID `bson:"_id,omitempty"`
Title string `bson:"title"`
Author string `bson:"author"`
Year int `bson:"year"`
Tags []string `bson:"tags,omitempty"`
Stock int `bson:"stock"`
CreatedAt time.Time `bson:"created_at"`
}
- Every document has an
_idfield. Withomitemptyon a zeroObjectID, the field is left out and the driver generates a newObjectIDon insert. - Without a tag, the field name is lowercased (
CreatedAtbecomescreatedat), so it's best to always use tags. time.Timeis stored as a BSON date with millisecond precision, in UTC.
For ad-hoc documents, filters and updates the bson package provides:
bson.D- an ordered document, a slice ofbson.E{Key, Value}. Use it for filters, updates, sort specs and pipelines where order matters.bson.M- an unorderedmap[string]any. Convenient when order doesn't matter.bson.A- an array.
filter := bson.D{{"author", "Jon Bodner"}, {"year", bson.D{{"$gte", 2020}}}}
filter2 := bson.M{"author": "Jon Bodner", "year": bson.M{"$gte": 2020}}
tags := bson.A{"go", "programming"}
go vet warns about unkeyed bson.E fields in bson.D{{"k", v}}. This short form is what the official documentation uses; you can write bson.E{Key: "k", Value: v} if you prefer.
Inserting documents
b := Book{
Title: "The Go Programming Language",
Author: "Alan Donovan",
Year: 2015,
Tags: []string{"go", "programming"},
Stock: 3,
CreatedAt: time.Now(),
}
res, err := coll.InsertOne(ctx, b)
if err != nil {
log.Fatal(err)
}
id := res.InsertedID.(bson.ObjectID)
fmt.Println("inserted id:", id.Hex())
books := []Book{
{Title: "Learning Go", Author: "Jon Bodner", Year: 2024, Tags: []string{"go"}, Stock: 5},
{Title: "Concurrency in Go", Author: "Katherine Cox-Buday", Year: 2017, Tags: []string{"go", "concurrency"}, Stock: 0},
{Title: "Designing Data-Intensive Applications", Author: "Martin Kleppmann", Year: 2017, Tags: []string{"databases"}, Stock: 2},
}
many, err := coll.InsertMany(ctx, books)
if err != nil {
log.Fatal(err)
}
fmt.Println("inserted", len(many.InsertedIDs), "documents")
inserted id: 6711a3c2f1d2e4b5a6c7d8e9
inserted 3 documents
InsertedID has type any because _id can be any BSON value. Here it's an ObjectID generated by the driver. InsertMany accepts any slice since v2 (in v1 it required []interface{}).
Finding one document
FindOne returns a *SingleResult; call Decode to get the document. When nothing matches, Decode returns mongo.ErrNoDocuments:
var b Book
err := coll.FindOne(ctx, bson.D{{"title", "Learning Go"}}).Decode(&b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s by %s (%d)\n", b.Title, b.Author, b.Year)
err = coll.FindOne(ctx, bson.D{{"title", "No Such Book"}}).Decode(&b)
if errors.Is(err, mongo.ErrNoDocuments) {
fmt.Println("not found")
} else if err != nil {
log.Fatal(err)
}
Learning Go by Jon Bodner (2024)
not found
To find by id, convert the hex string first: id, err := bson.ObjectIDFromHex(s) and filter with bson.D{{"_id", id}}. Filtering by the string itself won't match.
Finding many documents
Find returns a cursor. Options for sorting, limiting and projection (choosing which fields to return) are built with options.Find():
filter := bson.D{
{"tags", "go"}, // array contains "go"
{"year", bson.D{{"$gte", 2016}}}, // year >= 2016
}
opts := options.Find().
SetSort(bson.D{{"year", -1}}).
SetLimit(10).
SetProjection(bson.D{{"title", 1}, {"year", 1}})
cursor, err := coll.Find(ctx, filter, opts)
if err != nil {
log.Fatal(err)
}
var books []Book
if err := cursor.All(ctx, &books); err != nil {
log.Fatal(err)
}
for _, b := range books {
fmt.Printf("%d %s author=%q\n", b.Year, b.Title, b.Author)
}
2024 Learning Go author=""
2017 Concurrency in Go author=""
Author is empty because the projection didn't include it. cursor.All decodes everything into a slice and closes the cursor. Use bson.D{} (not nil) as the filter to match all documents.
For large result sets, iterate instead of loading everything into memory. The driver fetches documents from the server in batches as you go:
cursor, err := coll.Find(ctx, bson.D{{"stock", bson.D{{"$gt", 0}}}},
options.Find().SetSort(bson.D{{"title", 1}}))
if err != nil {
log.Fatal(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var b Book
if err := cursor.Decode(&b); err != nil {
log.Fatal(err)
}
fmt.Printf("%-40s stock=%d\n", b.Title, b.Stock)
}
if err := cursor.Err(); err != nil {
log.Fatal(err)
}
Designing Data-Intensive Applications stock=2
Learning Go stock=5
The Go Programming Language stock=3
Always check cursor.Err() after the loop: Next returns false both at the end and on error.
If you don't have a struct, decode into bson.M. Note that arrays decode as bson.A:
var doc bson.M
err := coll.FindOne(ctx, bson.M{"author": "Jon Bodner"},
options.FindOne().SetProjection(bson.M{"_id": 0, "title": 1, "tags": 1})).Decode(&doc)
if err != nil {
log.Fatal(err)
}
fmt.Println(doc)
fmt.Printf("%T\n", doc["tags"])
{"title":"Learning Go","tags":["go"]}
bson.A
Updating documents
Updates use operators like $set, $inc, $push, $addToSet and $unset. UpdateOne changes the first matching document, UpdateMany all of them:
res, err := coll.UpdateOne(ctx,
bson.D{{"title", "Learning Go"}},
bson.D{
{"$inc", bson.D{{"stock", -1}}},
{"$addToSet", bson.D{{"tags", "beginner"}}},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("matched:", res.MatchedCount, "modified:", res.ModifiedCount)
res, err = coll.UpdateMany(ctx,
bson.D{{"year", bson.D{{"$lt", 2018}}}},
bson.D{{"$set", bson.D{{"classic", true}}}})
if err != nil {
log.Fatal(err)
}
fmt.Println("matched:", res.MatchedCount, "modified:", res.ModifiedCount)
matched: 1 modified: 1
matched: 3 modified: 3
An upsert inserts a new document when the filter matches nothing. The new document is built from the equality fields in the filter plus the update:
res, err = coll.UpdateOne(ctx,
bson.D{{"title", "100 Go Mistakes"}},
bson.D{
{"$set", bson.D{{"author", "Teiva Harsanyi"}, {"year", 2022}}},
{"$inc", bson.D{{"stock", 1}}},
},
options.UpdateOne().SetUpsert(true))
if err != nil {
log.Fatal(err)
}
fmt.Println("upserted:", res.UpsertedCount)
upserted: 1
To update and get the document back in one atomic operation use FindOneAndUpdate. By default it returns the document as it was before the update; ask for the new version with SetReturnDocument(options.After):
var after Book
err = coll.FindOneAndUpdate(ctx,
bson.D{{"title", "Concurrency in Go"}},
bson.D{{"$inc", bson.D{{"stock", 10}}}},
options.FindOneAndUpdate().SetReturnDocument(options.After)).Decode(&after)
if err != nil {
log.Fatal(err)
}
fmt.Println("new stock:", after.Stock)
new stock: 10
ReplaceOne(ctx, filter, book) replaces the whole document (except _id) with a new one.
Deleting and counting
n, err := coll.CountDocuments(ctx, bson.D{})
if err != nil {
log.Fatal(err)
}
fmt.Println("before:", n)
res, err := coll.DeleteMany(ctx, bson.D{{"classic", true}, {"tags", "databases"}})
if err != nil {
log.Fatal(err)
}
fmt.Println("deleted:", res.DeletedCount)
n, _ = coll.CountDocuments(ctx, bson.D{})
fmt.Println("after:", n)
before: 5
deleted: 1
after: 4
DeleteOne removes only the first match. For a fast, approximate count of the whole collection use EstimatedDocumentCount, which reads collection metadata instead of scanning.
Indexes
Without an index, queries scan the whole collection. Create indexes at application startup; CreateOne is a no-op if an identical index already exists:
name, err := coll.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{"title", 1}},
Options: options.Index().SetUnique(true),
})
if err != nil {
log.Fatal(err)
}
fmt.Println("created index:", name)
_, err = coll.InsertOne(ctx, Book{Title: "Learning Go", Author: "Someone Else"})
if mongo.IsDuplicateKeyError(err) {
fmt.Println("duplicate title rejected")
} else if err != nil {
log.Fatal(err)
}
created index: title_1
duplicate title rejected
1 means ascending and -1 descending. A compound index lists several keys: bson.D{{"author", 1}, {"year", -1}}.
Aggregation
The aggregation pipeline transforms documents through a sequence of stages. mongo.Pipeline is a []bson.D, one element per stage. Here we count books and total stock per tag:
pipeline := mongo.Pipeline{
{{"$unwind", "$tags"}},
{{"$group", bson.D{
{"_id", "$tags"},
{"books", bson.D{{"$sum", 1}}},
{"stock", bson.D{{"$sum", "$stock"}}},
}}},
{{"$sort", bson.D{{"books", -1}, {"_id", 1}}}},
}
cursor, err := coll.Aggregate(ctx, pipeline)
if err != nil {
log.Fatal(err)
}
var results []struct {
Tag string `bson:"_id"`
Books int `bson:"books"`
Stock int `bson:"stock"`
}
if err := cursor.All(ctx, &results); err != nil {
log.Fatal(err)
}
for _, r := range results {
fmt.Printf("%-12s books=%d stock=%d\n", r.Tag, r.Books, r.Stock)
}
go books=3 stock=17
beginner books=1 stock=4
concurrency books=1 stock=10
programming books=1 stock=3
Put $match stages first so they can use indexes and reduce the amount of data flowing through the rest of the pipeline.
Transactions
A single-document write is always atomic. To change multiple documents atomically, use a transaction (requires a replica set or sharded cluster). WithTransaction starts the transaction, runs your callback, commits, and retries the whole callback on transient errors:
orders := client.Database("bookstore").Collection("orders")
session, err := client.StartSession()
if err != nil {
log.Fatal(err)
}
defer session.EndSession(ctx)
_, err = session.WithTransaction(ctx, func(ctx context.Context) (any, error) {
res, err := coll.UpdateOne(ctx,
bson.D{{"title", "Learning Go"}, {"stock", bson.D{{"$gt", 0}}}},
bson.D{{"$inc", bson.D{{"stock", -1}}}})
if err != nil {
return nil, err
}
if res.ModifiedCount == 0 {
return nil, errors.New("out of stock") // aborts the transaction
}
_, err = orders.InsertOne(ctx, bson.D{{"title", "Learning Go"}, {"qty", 1}})
return nil, err
})
if err != nil {
log.Fatal(err)
}
fmt.Println("order placed")
order placed
Inside the callback you must pass the callback's ctx to every operation. It carries the session; using the outer context would run the operation outside the transaction. Since the callback may run more than once, it shouldn't have side effects other than database writes.
Differences from driver v1
If you're porting code from v1:
- Import paths gained
/v2:go.mongodb.org/mongo-driver/v2/mongo,.../v2/bson. mongo.Connect(ctx, opts)becamemongo.Connect(opts).primitive.ObjectIDmoved tobson.ObjectID; thebson/primitivepackage is gone (primitive.NewObjectID()is nowbson.NewObjectID()).- Options are builders, and some were split:
options.Update()becameoptions.UpdateOne()/options.UpdateMany(). - The transaction callback takes a plain
context.Contextinstead ofmongo.SessionContext. Distinctreturns a*mongo.DistinctResultthat youDecodeinto a slice.
For relational databases see SQL.