Skip to content

MongoDB with Go: CRUD, Filters, Generics Helpers, Relationships ​

"The MongoDB supported driver for Go." — README of the mongo-go-driver repository, v2.8.2

Summary: the official mongo-go-driver v2 (go.mongodb.org/mongo-driver/v2) turns Go structs into BSON documents and back, runs CRUD, filters, updates, indexes, aggregation, transactions and change streams, and takes a context.Context on every call that touches the network; this chapter builds a small, testable data layer on it with a generic Repository[T]. Focus: mongo.Connect, options.Client and .ApplyURI, Ping/Disconnect, pool and timeout options, bson.D vs bson.M, struct tags (_id, omitempty, inline), InsertOne/InsertMany, FindOne, Find with a cursor (Next, Decode, All, Close), filter operators, projections, sort, limit/skip vs range pagination on _id, UpdateOne/UpdateMany with $set/$inc/$push/$addToSet, upserts, ReplaceOne, DeleteOne, FindOneAndUpdate, bulk writes, indexes (unique, compound, TTL, text), the aggregation pipeline, typed filters and Repository[T], embedding vs referencing and $lookup, transactions with WithTransaction, read/write concerns, change streams, error handling (mongo.ErrNoDocuments, duplicate key 11000), $jsonSchema validation and testing without a server. Learning goal: Open one client for the life of the process, map documents to structs with tags you can explain, write every query as an ordered, typed bson.D, page with a range on _id, keep related data in one document when it is read together and in a second collection when it is not, wrap multi-document writes in WithTransaction only when a replica set is available, translate driver errors into your own domain errors, and test the whole layer against an interface and a fake.

This page owns the Go driver: connecting, mapping, querying, updating, indexing, aggregating and testing from Go. It does not re-teach the server. MongoDB itself (the document model, replica sets, sharding, WiredTiger) is in MongoDB in Depth; the map of document, key-value, wide-column and graph stores is in NoSQL: Families & Data Models; how to shape tables and documents is in Schema Design, Normalization & Data Types. On the Go side: generics syntax is in Generics, struct tags and JSON in JSON, XML, Struct Tags, Encoder/Decoder, cancellation and deadlines in context, the SQL equivalent of this chapter in database/sql & pgx, and where the repository plugs into HTTP handlers in A REST API in Go. A command-sized summary of the shell is in the MongoDB Cheatsheet.

Facts below were checked against the mongo-go-driver v2.8.2 source and README on GitHub, its 1.x to 2.0 migration guide, the Go driver documentation on mongodb.com, the MongoDB Server manual (data modeling, transactions, indexes, aggregation, $jsonSchema, change streams, GridFS, error codes), the Laravel 13 MongoDB page, the Laravel MongoDB package documentation and the Go 1.18 and 1.24 release notes. pkg.go.dev returns 403 to scripted fetches, so API facts come from the tagged source. The snippets declare go 1.24 and pin the driver to v2.8.2, the newest release whose go.mod still says go 1.19; v2.9.0 and later declare go 1.25.0. They were compiled, vetted and tested with -race on Go 1.27.4 (macOS). No MongoDB server was available on the build machine: the tests use the driver's own constructors (mongo.NewCursorFromDocuments, mongo.NewSingleResultFromDocument) and fakes, and every lab step that needs a server is labelled "expected, not run".

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why a Go service needs a data layer around the driverWhy it exists
Which driver, which version, what changed in v2Where it comes from
A before/after of a query layerGo
mongo.Connect, ApplyURI, Ping, Disconnect, pool size, timeoutsConnecting
bson.D, bson.M, bson.A, bson.EBSON types
Struct tags, _id, ObjectID, omitempty, inline, timeMapping structs
InsertOne, InsertManyInsert
FindOne, ErrNoDocumentsFindOne
Find, cursors, Next, Decode, All, CloseFind and cursors
$eq, $gt, $in, $regex, $elemMatchFilters
Projections and sortProjection and sort
limit/skip vs range pagination on _idPagination
UpdateOne, UpdateMany, $set, $inc, $push, $addToSetUpdate
Upsert, ReplaceOne, FindOneAndUpdateUpsert, replace, find-and-modify
DeleteOne, DeleteManyDelete
Bulk writeBulk write
Unique, compound, TTL, text indexesIndexes
$match, $group, $lookup, $unwind, $projectAggregation
Type-checked filtersTyped filters
Repository[T]Generic repository
Embedding vs referencing, $lookup, denormalizationRelationships
Sessions, WithTransaction, replica set requirementTransactions
Read concern, write concernRead and write concerns
Change streams, GridFSChange streams and GridFS
Duplicate key 11000, IsDuplicateKeyError, timeoutsError handling
$jsonSchemaSchema validation
Fakes, testcontainersTesting
Common bugs and fixesSolving the classic problems
What to use whenChoosing
Monolith to distributedIn architecture
Run the tests yourselfLab
Eloquent and the Laravel MongoDB packageFor PHP/Laravel developers

Everything in one minute ​

The write path and the read path. Every call is a method on *mongo.Collection, takes a ctx first, and returns a result struct or a cursor. Each row is unpacked in the concept catalogue.

GoalMethodReturns"Nothing matched" isTypical use
Add one documentInsertOne*InsertOneResult with InsertedIDnot applicableCreate a user
Add manyInsertMany*InsertManyResultnot applicableImport a batch
Read oneFindOne(...).Decode(&v)*SingleResulterror mongo.ErrNoDocumentsLoad by id or email
Read manyFind then Next/Decode or All*Cursoran empty cursor, no errorLists, exports
Change oneUpdateOne*UpdateResultMatchedCount == 0, no error$set, $inc
Change manyUpdateMany*UpdateResultMatchedCount == 0, no errorBulk status change
Swap a whole documentReplaceOne*UpdateResultMatchedCount == 0, no errorFull save
Change and read backFindOneAndUpdate*SingleResulterror ErrNoDocumentsCounters, queues
RemoveDeleteOne, DeleteMany*DeleteResultDeletedCount == 0, no errorDelete by id
Several writes, one request per batch of up to 100,000BulkWrite*BulkWriteResultcounts per modelSync jobs
CountCountDocumentsint640Exact counts
ReportAggregate*Cursoran empty cursorGroup, join, reshape

The BSON building blocks. The driver names four types for BSON data: D ordered document, M unordered map, A array, E one element of a D.

TypeOrder kept?Use forNever use for
bson.DYes (a slice of bson.E)Filters with several keys, sort, index keys, commands, pipelines stagesNothing: it is the safe default
bson.MNo (a Go map)Reading a document whose shape you do not knowSort documents, index keys, the first key of a command
bson.AYesArrays inside filters and updates ($and, $in)n/a
bson.En/aOne Key/Value pairn/a
bson.RawYes (bytes)Zero-copy reads, change event payloadsBuilding queries

The errors you will handle.

Text or valueWhere it comes fromMeaningRetry?
mongo: no documents in result (mongo.ErrNoDocuments)FindOne, FindOneAndUpdate, FindOneAndDeleteNothing matchedNo: map to "not found"
E11000 duplicate key error (code 11000, DuplicateKey)InsertOne, UpdateOne with upsert, InsertManyA unique index was violatedNo: map to "conflict"
server selection error: context deadline exceededany call, PingNo suitable server within the server selection timeoutMaybe, with backoff
context deadline exceeded (mongo.IsTimeout)any call with a ctx or a client TimeoutYour budget endedOnly if budget remains
TransientTransactionError labelinside a transactionWhole transaction can be re-runYes, WithTransaction does it
a server error when a transaction starts (the message differs between server versions)transaction on a standalone serverNo replica set; standalone deployments do not support transactionsNo: fix the deployment

Why it exists ​

The driver gives you the primitives: a collection handle, bson values and a cursor. A real service needs more than primitives. It needs one place that knows the collection name and the document shape, one place that turns driver errors into the errors the rest of the code understands, one place where filters are built from typed values rather than from request JSON, and a seam where a test can replace the database. Without that seam every handler holds a *mongo.Collection, builds bson.M from map[string]any, forgets to close a cursor and can only be tested against a running server.

Raw driver calls in handlersA small data layer
Filters assembled from request mapsFilters built from typed values
mongo.ErrNoDocuments leaks into HTTP codeErrNotFound is the only "missing" the callers know
Every test needs mongodMost tests use a fake behind an interface
Collection names and field names as string literals everywhereDeclared once as constants and typed fields
Less code at firstA few hundred lines that you write once and reuse

An everyday picture. A filing cabinet in a clinic. The drawer is the collection, a folder is a document, and the folder may hold loose pages inside it (embedded data) or a note "see file 4711" (a reference). The receptionist (the repository) is the only person who opens the drawer: she knows the labelling rules, tells the doctor "no such patient" instead of walking in with an empty hand, and refuses to file two folders under the same number. If the receptionist is away, a colleague with a cardboard copy of the drawer (a fake) can rehearse the whole routine.

Three common misunderstandings, up front ​

  1. "MongoDB has no schema, so my struct can change freely." The server does not enforce a shape unless you ask for one, but your Go struct is a schema in the code, and a field renamed in Go silently stops reading old documents. Tags, versions of documents and $jsonSchema are how you take control (see Mapping structs and Schema validation).
  2. "mongo.Connect connects." It creates the client and starts background monitors; it does not prove that a server answers. A wrong host first shows up as a server selection error on the first query, so call Ping at start-up (see Connecting).
  3. "A transaction makes everything safe, so I use one everywhere." Single-document writes are already atomic; transactions need a replica set or sharded cluster, add latency and may re-run your callback. Model data so that most writes touch one document (see Transactions).

Where it comes from ​

MongoDB, Inc. maintains the official Go driver in the mongodb/mongo-go-driver repository. Version 1.x lived at go.mongodb.org/mongo-driver. The 2.0 line moved to a new major import path, go.mongodb.org/mongo-driver/v2, and its migration guide recommends the mod upgrade --mod-name=go.mongodb.org/mongo-driver tool to rewrite imports. The changes that matter when you read older tutorials:

v1 habit (many blog posts)v2 (this chapter)
mongo.Connect(ctx, options.Client()...)mongo.Connect(options.Client()...): the context parameter was removed because the deployment connector "doesn’t accept a context"
client.Connect(ctx)removed, mongo.Connect returns a connected client
primitive.ObjectID from bson/primitivebson.ObjectID: the bson/primitive package was merged into bson
mongo.SessionContext callback argumenta plain context.Context that carries the session
SingleResult.DecodeBytesSingleResult.Raw
Option structs filled in directlyOption builders hold a slice of setter functions; options.Find().SetLimit(...) still works the same way
Cursor.SetMaxTimeCursor.SetMaxAwaitTime

The v2 README states the requirement as "Go 1.19 or higher" for the 2.8.x line and "MongoDB 4.2 and higher". Later 2.x releases moved the minimum to Go 1.25 (go.mod of v2.9.0 says go 1.25.0), which is why the snippets of this chapter pin v2.8.2 while keeping go 1.24 in their own go.mod. When you start a new project on Go 1.25 or newer, take the latest v2 instead.

Go generics arrived in Go 1.18, whose release notes say the language changes were "fully backward-compatible"; the data layer in this chapter uses them for exactly one thing: one repository written once for every document type.

Go ​

Before ​

The shape most first MongoDB code takes: a login filter copied from the request body into a bson.M, context.Background() in a function that serves a request, a cursor that is never closed, and skip pagination. It compiles, runs and works on a quiet day (its sort is already a bson.D: the driver refuses a multi-key bson.M as a sort, see BSON types). The test shows the problem: a request body {"email":"a@example.test","password":{"$ne":""}} turns the password clause into an operator and the filter sent to the server is {"email":"a@example.test","password":{"$ne":""}}, which matches every account with a password.

go
// Package before is the shape most first MongoDB code takes: untyped filters
// built from request data, context.Background everywhere, no Close, and a
// skip-based page. It compiles and runs, and it is still the wrong design.
package before

import (
	"context"

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

// LoginFilter copies whatever the client sent into the query. With the body
// {"email":"a@example.test","password":{"$ne":""}} the password clause becomes
// an operator and matches every account that has a password.
func LoginFilter(body map[string]any) bson.M {
	return bson.M{"email": body["email"], "password": body["password"]}
}

// UserSort is the sort FindUsers sends. The driver rejects a bson.M with more
// than one key as a sort (ErrMapForOrderedArgument), so even the "before" code
// has to use an ordered bson.D here.
func UserSort() any {
	return bson.D{{Key: "age", Value: -1}, {Key: "name", Value: 1}}
}

// FindUsers still has design smells: context.Background ignores the request's
// lifetime, the cursor is never closed, and skip pagination gets slower with
// every page. It does check its errors, so it runs.
func FindUsers(coll *mongo.Collection, page int64) ([]bson.M, error) {
	cur, err := coll.Find(context.Background(), bson.M{},
		options.Find().SetSort(UserSort()).SetSkip(page*20).SetLimit(20))
	if err != nil {
		return nil, err
	}
	var out []bson.M
	for cur.Next(context.Background()) {
		var doc bson.M
		if err := cur.Decode(&doc); err != nil {
			return nil, err
		}
		out = append(out, doc)
	}
	return out, cur.Err()
}
go
package before

import (
	"encoding/json"
	"testing"

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

func TestOperatorInjectionPassesThrough(t *testing.T) {
	var body map[string]any
	if err := json.Unmarshal([]byte(`{"email":"a@example.test","password":{"$ne":""}}`), &body); err != nil {
		t.Fatal(err)
	}
	raw, err := bson.Marshal(LoginFilter(body))
	if err != nil {
		t.Fatal(err)
	}
	v, err := bson.Raw(raw).LookupErr("password", "$ne")
	if err != nil {
		t.Fatalf("the injected $ne operator should survive in the filter: %v", err)
	}
	if v.StringValue() != "" {
		t.Fatalf("unexpected operand %v", v)
	}
	ej, _ := bson.MarshalExtJSON(LoginFilter(body), false, false)
	t.Logf("filter sent to the server: %s", ej)
}

// The sort used by FindUsers must be an ordered document. The driver rejects a
// bson.M with more than one key as a sort (ErrMapForOrderedArgument), so
// before-code that runs has to use bson.D.
func TestSortIsOrdered(t *testing.T) {
	d, ok := UserSort().(bson.D)
	if !ok {
		t.Fatalf("UserSort must be a bson.D, got %T", UserSort())
	}
	b, err := bson.MarshalExtJSON(d, false, false)
	if err != nil || string(b) != `{"age":-1,"name":1}` {
		t.Fatalf("sort = %s err=%v", b, err)
	}
}

After ​

The same two functions with typed inputs, the caller's context, a closed cursor, checked errors, an ordered sort and range pagination. A password never appears in the query: Authenticate loads the user by email through a Users interface (the MongoDB-backed Store wraps Repository[User]), then compares the stored bcrypt hash in Go; an unknown email and a wrong password both return ErrBadCredentials (see Authentication in Go for hashing choices). The tests use a fake Users and prove that valid, wrong, unknown and infrastructure-failure cases behave as described and that the query holds only the email. The tests also prove that a JSON object in the password field does not decode into a string field at all.

go
// Package after fixes the same two functions: typed inputs that cannot become
// operators, the caller's context, closed cursors, checked errors and ordered
// sort keys.
package after

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"golang.org/x/crypto/bcrypt"

	"academy/mongodb-with-go/filters"
	"academy/mongodb-with-go/models"
	"academy/mongodb-with-go/repo"
)

// LoginFilter takes a string, so a JSON object in the request fails to decode
// before it gets here. Only the email is in the query.
func LoginFilter(email string) bson.D {
	return filters.ByEmail(email)
}

// ErrBadCredentials is returned for an unknown email and for a wrong password
// alike, so the caller cannot tell which accounts exist.
var ErrBadCredentials = errors.New("after: bad credentials")

// Users loads a user by email. Store is the MongoDB implementation.
type Users interface {
	FindByEmail(ctx context.Context, email string) (*models.User, error)
}

// Store implements Users on top of the generic repository.
type Store struct{ R *repo.Repository[models.User] }

// FindByEmail runs the typed email filter.
func (s Store) FindByEmail(ctx context.Context, email string) (*models.User, error) {
	return s.R.Get(ctx, LoginFilter(email))
}

// HashPassword returns a bcrypt hash. Real systems follow the choices in the
// authentication chapter (Argon2id or bcrypt with a tuned cost).
func HashPassword(password string) string {
	h, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err) // only for a password longer than 72 bytes
	}
	return string(h)
}

// Authenticate loads the user by email and compares the stored hash in Go. The
// password never appears in a query, so no operator can be smuggled into it.
func Authenticate(ctx context.Context, users Users, email, password string) (*models.User, error) {
	u, err := users.FindByEmail(ctx, email)
	if errors.Is(err, repo.ErrNotFound) {
		return nil, ErrBadCredentials
	}
	if err != nil {
		return nil, err
	}
	if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil {
		return nil, ErrBadCredentials
	}
	return u, nil
}

// FindUsers streams one page of users with range pagination on _id.
func FindUsers(ctx context.Context, coll *mongo.Collection, last bson.ObjectID) ([]models.User, error) {
	filter, opts := filters.After(last, 20)
	cur, err := coll.Find(ctx, filter, opts.SetSort(filters.Sort(filters.Key{Field: "_id"})))
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)

	var out []models.User
	if err := cur.All(ctx, &out); err != nil {
		return nil, err
	}
	return out, nil
}

// SortOptions shows the ordered form of the sort that before.FindUsers got wrong.
func SortOptions() *options.FindOptionsBuilder {
	return options.Find().SetSort(filters.Sort(
		filters.Key{Field: "age", Desc: true},
		filters.Key{Field: "name"},
	))
}
go
package after

import (
	"context"
	"encoding/json"
	"errors"
	"testing"

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

	"academy/mongodb-with-go/filters"
	"academy/mongodb-with-go/models"
	"academy/mongodb-with-go/repo"
)

func TestObjectInPasswordFieldDoesNotDecodeIntoString(t *testing.T) {
	var req struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	err := json.Unmarshal([]byte(`{"email":"a@example.test","password":{"$ne":""}}`), &req)
	if err == nil {
		t.Fatal("an object must not decode into a string field")
	}
}

func TestEmailStaysAValueEvenIfItLooksLikeAnOperator(t *testing.T) {
	b, err := bson.MarshalExtJSON(LoginFilter(`{"$ne":""}`), false, false)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != `{"email":"{\"$ne\":\"\"}"}` {
		t.Fatalf("got %s", b)
	}
}

func TestSortKeepsOrder(t *testing.T) {
	o := &options.FindOptions{}
	for _, set := range SortOptions().List() {
		if err := set(o); err != nil {
			t.Fatal(err)
		}
	}
	b, _ := bson.MarshalExtJSON(o.Sort, false, false)
	if string(b) != `{"age":-1,"name":1}` {
		t.Fatalf("got %s", b)
	}
}

type fakeUsers struct {
	u   *models.User
	err error
	got bson.D
}

func (f *fakeUsers) FindByEmail(_ context.Context, email string) (*models.User, error) {
	f.got = filters.ByEmail(email)
	return f.u, f.err
}

func TestAuthenticate(t *testing.T) {
	hash := HashPassword("correct horse")
	u := &models.User{Email: "a@example.test", PasswordHash: hash}
	ctx := context.Background()

	if got, err := Authenticate(ctx, &fakeUsers{u: u}, "a@example.test", "correct horse"); err != nil || got.Email != "a@example.test" {
		t.Fatalf("valid login: %v %v", got, err)
	}
	if _, err := Authenticate(ctx, &fakeUsers{u: u}, "a@example.test", "wrong"); !errors.Is(err, ErrBadCredentials) {
		t.Fatalf("wrong password: %v", err)
	}
	if _, err := Authenticate(ctx, &fakeUsers{err: repo.ErrNotFound}, "x@example.test", "whatever"); !errors.Is(err, ErrBadCredentials) {
		t.Fatalf("unknown user must look like a wrong password, got %v", err)
	}
	boom := errors.New("db down")
	if _, err := Authenticate(ctx, &fakeUsers{err: boom}, "a@example.test", "x"); !errors.Is(err, boom) {
		t.Fatalf("infrastructure errors pass through, got %v", err)
	}
}

func TestPasswordIsNeverInTheQuery(t *testing.T) {
	f := &fakeUsers{u: &models.User{PasswordHash: HashPassword("p")}}
	_, _ = Authenticate(context.Background(), f, "a@example.test", "p")
	b, _ := bson.MarshalExtJSON(f.got, false, false)
	if string(b) != `{"email":"a@example.test"}` {
		t.Fatalf("query = %s", b)
	}
}

The Go angle ​

Go's strengths show in three places. Static types: bson.D and a typed field wrapper make an operator position impossible to fill from user input. Interfaces: the repository asks for the six methods it uses, and *mongo.Collection satisfies them without any adapter, so a fake is a dozen lines. Context: every network call takes ctx, so a closed browser tab, a deadline or a shutdown reaches the database call (see context). The cost is verbosity: bson.D{{Key: "a", Value: 1}} is longer than a JavaScript literal, and the compiler cannot check field names inside strings, which is what the typed filters of this chapter reduce.

The concept catalogue ​

Connecting: Connect, ApplyURI, Ping, Disconnect and connection pool options Must-know ​

In plain words: One *mongo.Client per process. It owns a pool of connections to every server in the deployment and a few background goroutines that watch the servers. You create it once in main, hand it down, and disconnect it when the process stops.

Common misunderstanding: "mongo.Connect returns an error if the server is down." It returns an error only if the options are invalid. The driver documentation says it "does not validate that the MongoDB deployment is reachable. To verify that the deployment is reachable, call [Client.Ping]." A wrong host, a firewall or a stopped server appears on the first operation or on Ping, as a server selection error after the server selection timeout (30 seconds unless you change it).

Definition: mongo.Connect(opts ...*options.ClientOptions) (*mongo.Client, error) in go.mongodb.org/mongo-driver/v2/mongo. Build the options with options.Client() and chain setters. .ApplyURI(uri) parses a connection string (mongodb://host:27017/?maxPoolSize=50, or mongodb+srv://...). The order of setter calls matters: the doc comment says later setters "overwrite the values from previous option setter calls, including the ApplyURI method". Call ApplyURI first and the explicit setters after it, so code beats the URI. client.Ping(ctx, readpref.Primary()) runs a cheap command and fails with a server selection error "until the client's server selection timeout expires". client.Disconnect(ctx) "will shut down any monitoring goroutines, close the idle connection pool, and will wait until all the in use connections have been returned"; if ctx ends first, in-use connections are closed and in-flight operations fail.

main                          driver                               server
1  Connect(opts)  ──────────▶ validate options, start monitors      (no traffic needed yet)
2  Ping(ctx 2s)   ──────────▶ select a server ──────────────────▶ { ping: 1 }
3                 ◀────────── ok, or "server selection error"
4  ... handlers use the same client from many goroutines ...
5  Disconnect(ctx 5s) ──────▶ stop monitors, drain the pool, close sockets

Real scenario: a Kubernetes pod that starts before the database service is ready (Ping with a retry loop and a clear log line instead of a crash at the first request); a CLI that runs one query and exits (Connect, query, Disconnect with a short timeout); a test that must not hang for 30 seconds when no server exists (a short ServerSelectionTimeout; the snippet's test fails in 300 ms).

OptionSetterDefaultWhat it controls
Connection string.ApplyURI(uri)noneHosts, credentials, and any URI option
Pool upper boundSetMaxPoolSize(u) / maxPoolSize100Max connections per server; callers block when the pool is full; 0 means unlimited
Pool lower boundSetMinPoolSize(u) / minPoolSize0Connections kept warm
Idle timeSetMaxConnIdleTime(d) / maxIdleTimeMS0 (never)When an unused connection is closed
Server selectionSetServerSelectionTimeout(d)30 sHow long an operation waits for a usable server
Per-operation budgetSetTimeout(d) / timeoutMSnoneA deadline for each operation when the ctx has none
App nameSetAppName(s)noneShown in server logs and currentOp
go
// Package connect builds a client with explicit timeouts and a pool size,
// verifies it with Ping and closes it with Disconnect.
package connect

import (
	"context"
	"errors"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

// Config is what the application reads from its environment.
type Config struct {
	URI                    string
	MaxPoolSize            uint64
	MinPoolSize            uint64
	ServerSelectionTimeout time.Duration
	OperationTimeout       time.Duration // per operation, applied by the driver
	AppName                string
}

// Options turns the config into client options. ApplyURI comes first so the
// explicit setters below it win over anything in the connection string.
func Options(c Config) *options.ClientOptions {
	o := options.Client().ApplyURI(c.URI)
	if c.MaxPoolSize > 0 {
		o.SetMaxPoolSize(c.MaxPoolSize)
	}
	if c.MinPoolSize > 0 {
		o.SetMinPoolSize(c.MinPoolSize)
	}
	if c.ServerSelectionTimeout > 0 {
		o.SetServerSelectionTimeout(c.ServerSelectionTimeout)
	}
	if c.OperationTimeout > 0 {
		o.SetTimeout(c.OperationTimeout)
	}
	if c.AppName != "" {
		o.SetAppName(c.AppName)
	}
	return o
}

// Open creates the client and proves the deployment is reachable. Connect
// returns before any server is contacted, so without Ping a wrong host only
// shows up at the first query.
func Open(ctx context.Context, c Config, pingTimeout time.Duration) (*mongo.Client, error) {
	client, err := mongo.Connect(Options(c))
	if err != nil {
		return nil, fmt.Errorf("mongo connect: %w", err)
	}
	pctx, cancel := context.WithTimeout(ctx, pingTimeout)
	defer cancel()
	if err := client.Ping(pctx, readpref.Primary()); err != nil {
		// Release the background monitors even when the ping failed.
		_ = client.Disconnect(context.WithoutCancel(ctx))
		return nil, fmt.Errorf("mongo ping: %w", err)
	}
	return client, nil
}

// Close disconnects with a bounded wait; call it once, from main.
func Close(client *mongo.Client, wait time.Duration) error {
	ctx, cancel := context.WithTimeout(context.Background(), wait)
	defer cancel()
	if err := client.Disconnect(ctx); err != nil && !errors.Is(err, context.DeadlineExceeded) {
		return err
	}
	return nil
}

The test proves the precedence rule (URI says 5, setter says 20, result 20), that a URI value survives when no override is given, and that Open against a closed port fails after about 300 ms with the real driver message mongo ping: server selection error: context deadline exceeded, current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:1, Type: Unknown, Last error: dial tcp 127.0.0.1:1: connect: connection refused }, ] }.

go
package connect

import (
	"context"
	"testing"
	"time"
)

func TestOptionsOrderOfPrecedence(t *testing.T) {
	// The URI says 5, the explicit setter says 20: the setter is applied last.
	o := Options(Config{
		URI:                    "mongodb://127.0.0.1:27017/?maxPoolSize=5&appName=fromuri",
		MaxPoolSize:            20,
		ServerSelectionTimeout: 2 * time.Second,
		OperationTimeout:       3 * time.Second,
		AppName:                "shop-api",
	})
	if *o.MaxPoolSize != 20 {
		t.Fatalf("MaxPoolSize = %d, want 20", *o.MaxPoolSize)
	}
	if *o.ServerSelectionTimeout != 2*time.Second || *o.Timeout != 3*time.Second {
		t.Fatalf("timeouts %v %v", *o.ServerSelectionTimeout, *o.Timeout)
	}
	if *o.AppName != "shop-api" {
		t.Fatalf("AppName = %s", *o.AppName)
	}
	if len(o.Hosts) != 1 || o.Hosts[0] != "127.0.0.1:27017" {
		t.Fatalf("hosts = %v", o.Hosts)
	}
}

func TestURIValueSurvivesWhenNoOverride(t *testing.T) {
	o := Options(Config{URI: "mongodb://127.0.0.1:27017/?maxPoolSize=5"})
	if *o.MaxPoolSize != 5 {
		t.Fatalf("MaxPoolSize = %d, want 5 from the URI", *o.MaxPoolSize)
	}
}

// Nothing listens on port 1, so Ping must fail within the server selection
// timeout instead of hanging. No MongoDB server is needed for this test.
func TestOpenFailsFastWhenServerIsUnreachable(t *testing.T) {
	start := time.Now()
	client, err := Open(context.Background(), Config{
		URI:                    "mongodb://127.0.0.1:1/?directConnection=true",
		ServerSelectionTimeout: 300 * time.Millisecond,
	}, time.Second)
	if err == nil {
		_ = Close(client, time.Second)
		t.Fatal("expected an error: no server on port 1")
	}
	if d := time.Since(start); d > 3*time.Second {
		t.Fatalf("took %v, the timeouts did not apply", d)
	}
	t.Logf("failed after %v: %v", time.Since(start).Round(10*time.Millisecond), err)
}

func TestConnectRejectsBadScheme(t *testing.T) {
	if _, err := Open(context.Background(), Config{URI: "postgres://x"}, time.Second); err == nil {
		t.Fatal("a non-mongodb scheme must be rejected by Connect")
	}
}

Fix / how to use it: one client, created in main, Ping with a timeout, defer Close. Never create a client per request: each one starts its own monitors and pool. The pool belongs to the client, so MaxPoolSize is per client and per server (see Connection Pooling for sizing against the server's connection limit).

Context timeouts on every call Must-know ​

In plain words: Every collection method takes a ctx. If the ctx ends, the operation stops waiting and returns an error. You decide how long each call may take; the database does not.

Common misunderstanding: "A timeout on the context kills the query on the server." The client stops waiting and the driver abandons the operation; the server may finish it (or kill it, depending on the version and settings). A write whose ctx expired may still have been applied: treat a timeout on a write as an unknown outcome and make writes idempotent (see context and API Idempotency).

Definition: The driver honours the deadline of the ctx you pass. SetTimeout on the client "will only be honored if there is no deadline on the operation Context", and the deadline of the context wins. mongo.IsTimeout(err) reports whether an error "was caused by a timeout" anywhere in its chain.

handler (budget 800 ms)                driver                    server
1  ctx, cancel := WithTimeout(r.Context(), 300ms)
2  coll.FindOne(ctx, ...)  ─────────▶ select server, send ─────▶ run query
3  ... 300 ms pass ...
4                          ◀───────── context deadline exceeded (client stops waiting)
5  errors.Is(err, context.DeadlineExceeded) == true; mongo.IsTimeout(err) == true

Real scenario: an API endpoint with a 1 s budget gives the database 300 ms and falls back to a cache; a nightly export uses one long ctx and no per-call timeout; a payment write uses a longer budget and an idempotency key because its timeout is ambiguous.

Fix / how to use it: derive a child ctx per call from the request's ctx, defer cancel(), and let the client-level SetTimeout be the safety net for code that forgot. Do not use context.TODO() in service code, as the driver's own documentation examples do for brevity.

BSON types: bson.D ordered, bson.M, bson.A, bson.E Must-know ​

In plain words: BSON is the binary JSON-like format MongoDB stores and sends. In Go you write BSON values with four helper types. bson.D is a list of key/value pairs that keeps its order; bson.M is a Go map that does not.

Common misunderstanding: "bson.M is the same as bson.D but shorter." Order is part of MongoDB's protocol: the first key of a command is the command name, the order of sort keys is the order of sorting, the order of index keys is the index. A Go map iterates in random order, so the driver refuses it where order is the meaning: Find with a sort given as a bson.M of more than one key returns ErrMapForOrderedArgument (the driver source treats "a map with more than 1 element" as unordered, and the same check covers hint). Elsewhere a bson.M is accepted but serialises its keys in a different order from run to run: the test in the filters package serialises one six-key bson.M 200 times and, in the run recorded here, got 6 different orderings; bson.D always produced the same one.

Definition: bson.D is []bson.E, bson.E is struct{ Key string; Value any }, bson.M is map[string]any, bson.A is []any. Nested documents are bson.D inside bson.D. Write bson.D{{Key: "age", Value: bson.D{{Key: "$gt", Value: 30}}}}, with keyed fields so go vet stays quiet (the unkeyed form in the driver's documentation triggers the composites vet check). In v2, bson.D also implements json.Marshaler and prints as Extended JSON through String().

SituationUseWhy
Filter, update, projectionbson.DOrder-safe, nothing random
Sort, index keys, commandsbson.D (required)Order is meaning
Reading an unknown shapebson.M or bson.RawOrder does not matter, lookup by key
Typed resulta struct with tagsCompile-time field names
Many values for $in, $and[]T or bson.ABoth are arrays in BSON
go
// Package filters builds query documents, projections, sorts and pages.
// Every builder returns an ordered bson.D (or an options builder) and never
// splices user input into an operator position.
package filters

import (
	"regexp"

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

// ByEmail matches on equality. { email: "x" } is shorthand for { email: { $eq: "x" } }.
func ByEmail(email string) bson.D {
	return bson.D{{Key: "email", Value: email}}
}

// EmailEq is the explicit $eq form.
func EmailEq(email string) bson.D {
	return bson.D{{Key: "email", Value: bson.D{{Key: "$eq", Value: email}}}}
}

// OlderThan uses $gt.
func OlderThan(age int) bson.D {
	return bson.D{{Key: "age", Value: bson.D{{Key: "$gt", Value: age}}}}
}

// InCities uses $in; an empty list matches nothing. A nil slice would be
// encoded as null by default, so it is replaced by an empty array.
func InCities(cities ...string) bson.D {
	if cities == nil {
		cities = []string{}
	}
	return bson.D{{Key: "address.city", Value: bson.D{{Key: "$in", Value: cities}}}}
}

// NameContains uses $regex with the "i" option. The user text is quoted with
// regexp.QuoteMeta so it cannot become a pattern (ReDoS, accidental wildcards).
func NameContains(text string) bson.D {
	return bson.D{{Key: "name", Value: bson.D{
		{Key: "$regex", Value: regexp.QuoteMeta(text)},
		{Key: "$options", Value: "i"},
	}}}
}

// HasLineItem uses $elemMatch: one array element must satisfy both conditions.
func HasLineItem(sku string, minQty int) bson.D {
	return bson.D{{Key: "items", Value: bson.D{{Key: "$elemMatch", Value: bson.D{
		{Key: "sku", Value: sku},
		{Key: "qty", Value: bson.D{{Key: "$gte", Value: minQty}}},
	}}}}}
}

// And combines clauses explicitly.
func And(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$and", Value: arr}}
}

// Projection keeps only the named fields (plus _id, which is on by default).
func Projection(fields ...string) bson.D {
	p := make(bson.D, 0, len(fields))
	for _, f := range fields {
		p = append(p, bson.E{Key: f, Value: 1})
	}
	return p
}

// Sort builds an ordered sort document: the order of keys is the order of
// sorting, which is why it must be a bson.D and never a bson.M.
func Sort(keys ...Key) bson.D {
	s := make(bson.D, 0, len(keys))
	for _, k := range keys {
		dir := 1
		if k.Desc {
			dir = -1
		}
		s = append(s, bson.E{Key: k.Field, Value: dir})
	}
	return s
}

// Key is one sort key.
type Key struct {
	Field string
	Desc  bool
}

// SkipPage is limit/skip pagination: the server walks and discards
// skip documents, so page 10,000 costs 10,000 index entries.
func SkipPage(page, size int64) *options.FindOptionsBuilder {
	return options.Find().
		SetSort(Sort(Key{Field: "_id"})).
		SetSkip((page - 1) * size).
		SetLimit(size)
}

// After is range pagination on _id: "give me the next size documents after the
// last _id I saw". The cost does not grow with the page number.
func After(last bson.ObjectID, size int64) (bson.D, *options.FindOptionsBuilder) {
	filter := bson.D{}
	if !last.IsZero() {
		filter = bson.D{{Key: "_id", Value: bson.D{{Key: "$gt", Value: last}}}}
	}
	return filter, options.Find().SetSort(Sort(Key{Field: "_id"})).SetLimit(size)
}

// Resolve applies the setter functions of a builder to a plain options struct,
// which is how the tests read back what was configured.
func Resolve(b *options.FindOptionsBuilder) (*options.FindOptions, error) {
	o := &options.FindOptions{}
	for _, set := range b.List() {
		if err := set(o); err != nil {
			return nil, err
		}
	}
	return o, nil
}

Fix / how to use it: default to bson.D and keep a bson.M only for ad hoc reads. To see what your code will send, marshal it with bson.MarshalExtJSON(v, false, false); every test of this chapter asserts on that string, which needs no server.

Mapping structs: tags, _id ObjectID, omitempty, inline, time Must-know ​

In plain words: A struct tag tells the driver which key a Go field is stored under and a few special rules: skip it when empty, flatten it, or never store it. Without tags the driver lowercases the field name.

Common misunderstanding: "omitempty drops any zero value." It drops numbers, booleans and strings equal to their zero value, empty slices and maps, and nil pointers and interfaces. For structs, the package documentation says they are only empty "if the struct type implements Zeroer and the IsZero method returns true". time.Time and bson.ObjectID both have IsZero, so a zero time and a zero id are dropped; a plain struct value such as an Address stays as an empty sub-document, which is why User.Address is a pointer. A second trap: omitzero, known from encoding/json, is not a tag of this bson package in v2.8.2.

Definition: the tag key is bson: bson:"name,option". Options: omitempty, minsize (an int64 that fits in int32 is written as int32), truncate (doubles decode into integers by cutting the fraction), inline (flatten a struct or map field into the parent) and the name - (skip). Defaults without tags, from the driver documentation and confirmed by the test below: only exported fields; the key is the lowercase field name; an embedded struct without inline becomes a sub-document keyed by the lowercased type name; a nil pointer without omitempty is written as BSON null.

Every document has an _id. If you do not supply one, the driver generates a bson.ObjectID on insert (a 12-byte value whose first four bytes are a creation timestamp, usually shown as 24 hex characters). Tag the field bson:"_id,omitempty" so a zero id is left out and the driver (not an all-zero id) fills it. bson.ObjectIDFromHex parses the hex form and returns an error for bad input, which is how you validate an id from a URL; id.Timestamp() reads the embedded time.

Times are stored as BSON dates, milliseconds since the Unix epoch in UTC. A time.Time with nanoseconds loses everything below the millisecond on a round trip, and the location is not stored. Keep the time zone in your own field when it matters.

Tag or defaultEffect on marshalEffect on unmarshalTypical use
bson:"_id,omitempty" on bson.ObjectIDzero id omitted, the driver adds onefilled from the documentprimary key
bson:"email"key emailreads key emailstable names independent of Go field names
bson:"age,omitempty"0 omittedmissing key leaves 0optional numbers (careful: a real 0 is lost)
bson:"address,omitempty" on a pointernil omittedmissing key leaves niloptional sub-document
bson:",inline" on an embedded structits fields appear at the top levelits fields are read from the top levelshared audit fields
bson:"-"never writtennever readsecrets, transient values
bson:"n,minsize" on int64smaller BSON type when it fitsnormalsave space
no taglowercase field name; embedded struct is a sub-documentsamequick scripts only
Go                                   BSON stored
1  ID zero, Email "a@example.test"   { email: "a@example.test", name: "Ada", created_at: Date(...) }
2  (insert) driver adds ObjectID  ──▶ { _id: ObjectId("..."), email: ..., ... }
3  (read) Decode(&u)              ──▶ u.ID = that ObjectID, u.CreatedAt truncated to milliseconds
go
// Package models shows how struct tags map Go structs to BSON documents.
package models

import (
	"time"

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

// Audit is embedded with the inline option, so its fields appear at the top
// level of the document instead of under a sub-document.
type Audit struct {
	CreatedAt time.Time `bson:"created_at"`
	UpdatedAt time.Time `bson:"updated_at,omitempty"`
}

// Address is a value embedded as a sub-document.
type Address struct {
	Street  string `bson:"street"`
	City    string `bson:"city"`
	Country string `bson:"country"`
}

// User is the document stored in the users collection.
type User struct {
	// ID is the primary key. omitempty keeps a zero ObjectID out of the
	// document so that the server (or the driver) generates one on insert.
	ID      bson.ObjectID `bson:"_id,omitempty"`
	Email   string        `bson:"email"`
	Name    string        `bson:"name"`
	Age     int           `bson:"age,omitempty"`
	Tags    []string      `bson:"tags,omitempty"`
	Address *Address      `bson:"address,omitempty"`
	Audit   `bson:",inline"`

	// PasswordHash is a bcrypt hash, never the password itself.
	PasswordHash string `bson:"password_hash,omitempty"`

	// Password never reaches the database: "-" skips the field.
	Password string `bson:"-"`
}

// New returns a user stamped with now. Times are stored by MongoDB as
// milliseconds since the epoch, so sub-millisecond precision is lost.
func New(email, name string, now time.Time) User {
	return User{Email: email, Name: name, Audit: Audit{CreatedAt: now}}
}
go
package models

import (
	"testing"
	"time"

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

func mustMarshal(t *testing.T, v any) bson.Raw {
	t.Helper()
	b, err := bson.Marshal(v)
	if err != nil {
		t.Fatal(err)
	}
	return bson.Raw(b)
}

func TestZeroIDIsOmitted(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("_id"); err == nil {
		t.Fatal("zero ObjectID must be omitted by omitempty")
	}
}

func TestInlineFlattensAudit(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("created_at"); err != nil {
		t.Fatalf("created_at should be a top-level key: %v", err)
	}
	if _, err := raw.LookupErr("audit"); err == nil {
		t.Fatal("inline struct must not appear as a sub-document")
	}
}

func TestOmitEmptyDropsZeroTime(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("updated_at"); err == nil {
		t.Fatal("zero updated_at must be omitted by omitempty (time.Time implements Zeroer)")
	}
}

func TestPasswordIsSkipped(t *testing.T) {
	u := New("a@example.test", "Ada", time.Now())
	u.Password = "secret"
	raw := mustMarshal(t, u)
	if _, err := raw.LookupErr("Password"); err == nil {
		t.Fatal("password must not be stored")
	}
	if _, err := raw.LookupErr("password"); err == nil {
		t.Fatal("password must not be stored")
	}
}

func TestRoundTripTruncatesToMilliseconds(t *testing.T) {
	now := time.Date(2026, 11, 28, 10, 30, 15, 123456789, time.UTC)
	u := New("a@example.test", "Ada", now)
	u.ID = bson.NewObjectID()
	u.Address = &Address{City: "Berlin"}
	raw := mustMarshal(t, u)
	var back User
	if err := bson.Unmarshal(raw, &back); err != nil {
		t.Fatal(err)
	}
	if back.ID != u.ID || back.Address == nil || back.Address.City != "Berlin" {
		t.Fatalf("round trip lost data: %+v", back)
	}
	want := now.Truncate(time.Millisecond)
	if !back.CreatedAt.Equal(want) {
		t.Fatalf("created_at = %v, want %v", back.CreatedAt, want)
	}
}

func TestObjectIDCarriesCreationTime(t *testing.T) {
	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	id := bson.NewObjectIDFromTimestamp(at)
	if !id.Timestamp().Equal(at) {
		t.Fatalf("timestamp = %v, want %v", id.Timestamp(), at)
	}
	back, err := bson.ObjectIDFromHex(id.Hex())
	if err != nil || back != id {
		t.Fatalf("hex round trip failed: %v", err)
	}
	if len(id.Hex()) != 24 {
		t.Fatalf("hex length = %d, want 24", len(id.Hex()))
	}
}

// A struct without an IsZero method is never "empty": omitempty keeps it as an
// empty sub-document, which is why Address is a pointer in User.
func TestOmitEmptyKeepsPlainStructs(t *testing.T) {
	type wrap struct {
		A Address  `bson:"a,omitempty"`
		P *Address `bson:"p,omitempty"`
	}
	raw := mustMarshal(t, wrap{})
	if _, err := raw.LookupErr("a"); err != nil {
		t.Fatal("a plain struct value is kept even when zero")
	}
	if _, err := raw.LookupErr("p"); err == nil {
		t.Fatal("a nil pointer is omitted")
	}
}

// $jsonSchema bsonType "int" matches int32 only; "long" matches int64. A Go int
// that fits is written as int32, an int64 value as int64.
func TestGoIntBSONType(t *testing.T) {
	small := mustMarshal(t, bson.D{{Key: "n", Value: 5}})
	big := mustMarshal(t, bson.D{{Key: "n", Value: int64(1) << 40}})
	if got := small.Index(0).Value().Type; got != bson.TypeInt32 {
		t.Fatalf("small int type = %v, want int32", got)
	}
	if got := big.Index(0).Value().Type; got != bson.TypeInt64 {
		t.Fatalf("big int type = %v, want int64", got)
	}
}

// Without tags the driver lowercases the field name, stores an embedded struct
// as a sub-document keyed by its lowercased type name, and writes a nil pointer
// as BSON null. These are the defaults the tags above override.
func TestDefaultsWithoutTags(t *testing.T) {
	type Inner struct{ X int }
	type Plain struct {
		FullName string
		Inner
		Ptr *Address
	}
	raw := mustMarshal(t, Plain{FullName: "Ada"})
	if raw.Lookup("fullname").StringValue() != "Ada" {
		t.Fatal("default key is the lowercased field name")
	}
	if raw.Lookup("inner").Type != bson.TypeEmbeddedDocument {
		t.Fatal("an embedded struct without inline is a sub-document")
	}
	if raw.Lookup("ptr").Type != bson.TypeNull {
		t.Fatal("a nil pointer without omitempty is BSON null")
	}
}
Struct tags decide the shape of the stored documentGo struct UserID bson.ObjectID `bson:"_id,omitempty"`Email string `bson:"email"`Address *Address `bson:"address,omitempty"`Audit `bson:",inline"`Password string `bson:"-"`Age int `bson:"age,omitempty"`MarshalBSON document_id: absent, the driver adds an ObjectID on insertemail: "ada@example.test"address: absent while the pointer is nilcreated_at: Date, top level, millisecondspassword: never storedage: int32 when it fits, absent when 0Without tags: key = lowercased field name, embedded struct = sub-document, nil pointer = null.omitempty drops a plain struct value never, but drops time.Time and ObjectID when zero (they have IsZero).

Real scenario: an audit block (created_at, updated_at) shared by ten document types through an inline embedded struct; a password hash field with bson:"-" on the request type so it cannot be stored by accident; an optional deleted_at that is omitempty so live documents do not carry the key; an _id that is a string slug for a settings document instead of an ObjectID (then the field is string and has no omitempty).

Fix / how to use it: tag every field explicitly, name keys in snake_case, keep ids as bson.ObjectID unless the natural key is better, and keep a test that marshals each model and looks up the keys you query by (the snippet's tests do this). The same tags idea for JSON is in JSON, XML, Struct Tags; note that json and bson tags are separate, so a struct that crosses both needs both.

Insert: InsertOne/InsertMany Must-know ​

In plain words: InsertOne stores one document and tells you its _id. InsertMany stores a list, sent as one batch (the driver splits very large lists, see below).

Common misunderstanding: "InsertMany is all-or-nothing." By default it is ordered and stops at the first error, but the documents before the error stay inserted. With the unordered option it keeps going and reports every failure. Neither is a transaction.

Definition: coll.InsertOne(ctx, doc) returns *InsertOneResult{InsertedID any}; with a generated id, InsertedID holds a bson.ObjectID. coll.InsertMany(ctx, docs) takes []any and returns *InsertManyResult{InsertedIDs []any}. A violated unique index returns a mongo.WriteException (or mongo.BulkWriteException for many) containing a write error with code 11000.

app                                   mongod
1  InsertOne(ctx, user) ────────────▶ validate, assign _id if missing
2                                     write to collection and every index
3                       ◀──────────── { acknowledged: true, insertedId: ObjectId(...) }
4  second InsertOne, same email ────▶ unique index "email_unique" violated
5                       ◀──────────── WriteException: E11000 duplicate key error (code 11000)

Real scenario: registering a user (the unique index on email is the authority, not a FindOne before the insert, which has a race); importing 50,000 rows in batches of 1,000; seeding test data.

Fix / how to use it: insert a pointer to the struct, read the id from the result, and map code 11000 to your conflict error (see Error handling). For batches, chunk the input (one chunk is one request, so a chunk of a few thousand documents keeps memory use and retries sane).

FindOne and ErrNoDocuments Must-know ​

In plain words: FindOne returns the first document that matches. The query runs before FindOne returns; the SingleResult holds the answer (or the error), and Decode copies it into your value. "No match" is an error, not an empty value.

Common misunderstanding: "FindOne returns an error when the query fails, and nil when nothing matched." FindOne has no error return: the outcome, including a failed query, is read from the SingleResult through .Decode() or .Err(), and a miss is mongo.ErrNoDocuments ("mongo: no documents in result"), so you must compare with errors.Is. "First" without a sort means "whatever the server meets first", not the oldest.

Definition: coll.FindOne(ctx, filter, opts...) *mongo.SingleResult; SingleResult has Decode(v), Raw() and Err(); FindOne itself executes the find (it calls the same internal find as Find and reads the first result) before it returns. The source says that if the operation did not return any documents "all SingleResult methods will return ErrNoDocuments".

go
var u models.User
err := coll.FindOne(ctx, bson.D{{Key: "email", Value: email}}).Decode(&u)
switch {
case errors.Is(err, mongo.ErrNoDocuments):
	return nil, ErrNotFound // the caller's domain error
case err != nil:
	return nil, err
}

Real scenario: load a user by email at login; load a document by _id from a URL after ObjectIDFromHex; fetch a settings singleton.

Fix / how to use it: convert ErrNoDocuments at the repository boundary so no HTTP handler imports the driver, and add SetSort to the options when "first" must mean something.

Find with cursor: Next, Decode, All, Close Must-know ​

In plain words: Find does not return documents; it returns a cursor, a handle to a result that the server hands out in batches. You walk it with Next, copy each document with Decode, and close it when you are done.

Common misunderstanding: "I read the whole result, so the cursor is finished." A cursor holds server resources until it is exhausted or closed. The driver documentation says that if you retrieve documents one by one with Next, "always close the cursor to free the resources that it consumes", and Close "frees the resources your cursor consumes in both the client application and the MongoDB server". All closes the cursor itself ("This method will close the cursor after retrieving all documents"), but defer cur.Close(ctx) costs nothing and covers early returns.

Definition: coll.Find(ctx, filter, opts...) (*mongo.Cursor, error). cur.Next(ctx) bool advances; cur.Decode(&v) fills one value; cur.Err() reports the error that ended iteration (check it after the loop); cur.All(ctx, &slice) decodes everything into a slice pointer and completely overwrites it ("will be completely overwritten"); cur.Close(ctx) releases it. An empty result is an empty cursor, not an error.

app                                 driver                          server
1  Find(ctx, filter, limit 20) ──▶ send find ───────────────▶ run query, open cursor
2                              ◀── first batch of documents
3  Next → true, Decode × many      served from the local batch
4  Next → false at batch end   ──▶ getMore ───────────────────────▶ next batch
5  Next → false (exhausted), Err() == nil
6  Close(ctx)                  ──▶ killCursors if still open ─────▶ resources freed
Reading styleMemoryUse whenWatch out
All into []Twhole result at oncepage-sized results with a limitAn unbounded All on a large collection can use all memory
Next + Decodeone document at a timeexports, migrations, streaming JSONForgetting Close and Err()
Decode into bson.Rawno struct conversionpass-through proxiesYou parse by hand
TryNextlike Next but does not blocktailable cursors and change streamsReturns false on an empty batch, not only at the end

The repository of this chapter offers both: List uses All and Each streams with Next and Decode; both defer Close and check the errors.

Real scenario: a list endpoint (All, limit 50); a nightly export of ten million documents (Next plus a streaming writer); a migration that rewrites every document.

Fix / how to use it: always set a limit before All; use Next/Decode for anything that can be large; defer cur.Close(ctx) right after the error check; read cur.Err() after the loop.

Filters: $eq, $gt, $in, $regex, $elemMatch Must-know ​

In plain words: A filter is a document that describes the documents you want. A plain { email: "x" } means "email equals x"; operators starting with $ express everything else.

Common misunderstanding: "I can paste the request body into a filter, MongoDB sanitises it." Nothing sanitises operator keys: a value that is a JSON object becomes an operator document ({ "$ne": "" }), the operator injection the before example shows. And a $regex built from user text is a pattern, not a literal: a . matches anything and a bad pattern can be slow.

Definition: equality is the default ({ email: "x" } is shorthand for { email: { $eq: "x" } }); comparison operators $eq, $ne, $gt, $gte, $lt, $lte; set operators $in, $nin; logic $and, $or, $nor, $not; element $exists; arrays $elemMatch, $all, $size; text pattern $regex with $options (i for case-insensitive). Dotted keys reach into sub-documents and arrays (address.city). $elemMatch requires one array element to satisfy all its conditions together, which separate conditions on an array do not.

OperatorMeaningGo builder in the snippetIndex use
implicit equalityfield equals valuefilters.ByEmailyes
$eqexplicit equalityfilters.EmailEqyes
$gt, $gte, $lt, $lterangefilters.OlderThanyes (range scan)
$inequals any offilters.InCitiesyes (multi-point)
$regexpatternfilters.NameContains (quoted, i option)only anchored, case-sensitive prefix patterns use an index well
$elemMatchone array element matches allfilters.HasLineItemyes with a multikey index
$andall clausesfilters.Andper clause
$existskey presenttyped.Field.Existswith sparse or partial indexes

An empty $in list matches nothing, but a nil Go slice is encoded as BSON null by default (the client option NilSliceAsEmpty changes that), so filters.InCities and typed.Field.In replace nil with an empty slice; their tests assert {"$in":[]}. The filters test pins the exact documents sent: {"email":{"$eq":"a@example.test"}}, {"age":{"$gt":30}}, {"address.city":{"$in":["Berlin","Oslo"]}}, {"name":{"$regex":"a\\.b","$options":"i"}} (the dot escaped by regexp.QuoteMeta) and {"items":{"$elemMatch":{"sku":"SKU-1","qty":{"$gte":2}}}}.

Real scenario: a shop filter (status in (...), total > 100); a user search by name fragment; "orders that contain at least two units of SKU-1" ($elemMatch, not two separate conditions that could match different lines).

Fix / how to use it: take typed Go values (string, int, []string) into builder functions, never map[string]any; quote regex input; prefer anchored patterns or a text index for search (see Indexes).

Projection and sort Important ​

In plain words: A projection says which fields to send back; a sort says in which order. Smaller documents travel faster, and a sort without an index is slow.

Common misunderstanding: "I can sort by two fields with a bson.M." A map has no order, so the driver rejects a sort given as a bson.M with more than one key (ErrMapForOrderedArgument, returned by Find and FindOne). Use bson.D. Also, "sort" on a field with ties does not give a stable order across pages unless the last sort key is unique.

Definition: options.Find().SetProjection(bson.D{{Key: "email", Value: 1}}) includes fields (and _id unless you exclude it with 0); SetSort(bson.D{{Key: "age", Value: -1}, {Key: "name", Value: 1}}) sorts descending by age then ascending by name; SetLimit(n) and SetSkip(n) bound the result. In v2 these setters are on *options.FindOptionsBuilder and Find accepts the builder directly.

Real scenario: an autocomplete that needs only name and _id; a leaderboard sorted by score descending then by id; an export that excludes a large payload field.

Fix / how to use it: filters.Projection("email", "name") and filters.Sort(filters.Key{...}) in the snippet build ordered documents; the test shows {"age":-1,"name":1} comes out in the order written. A sort that no index supports runs in memory on the server. The manual says that stages needing more than 100 megabytes (it lists $sort "when the sort operation is not supported by an index") write temporary files to disk when allowDiskUse is true or the server parameter allowDiskUseByDefault is true (since MongoDB 6.0), and raise an error when it is false; either way a sort over a large result is slow, so index your sort (see Indexes).

Pagination: limit/skip vs range pagination on _id Must-know ​

In plain words: "Page 3" can mean "skip the first 40 and take 20" or "take the 20 after the last one I showed you". The first gets slower with every page; the second does not.

Common misunderstanding: "skip jumps to the page." The server must walk past the skipped documents, in sort order, before it returns the next ones, so deep pages cost time in proportion to the offset. The manual also tells you to sort on a field with unique values before you use skip, otherwise pages can overlap or miss documents.

Definition: limit/skip: SetSort(_id).SetSkip((page-1)*size).SetLimit(size). Range pagination, also called keyset or cursor pagination: remember the last _id of the previous page and filter { _id: { $gt: last } }, sorted by _id, limited to size. The cost is an index seek, constant in the page number. The trade-off: no "jump to page 500", and the sort key must be unique and indexed (_id always is). The SQL form of the same idea is in Pagination: Offset vs Keyset.

limit/skip, page 3, size 20                     range on _id, after id X, size 20
1  scan index from the start                   1  seek index to X (one B-tree descent)
2  discard 40 entries                          2  read the next 20 entries
3  return 20                                   3  return 20, remember the last _id
   cost grows with the page number                cost does not depend on the page number
Aspectlimit + skipRange on _id
Cost of page Ngrows with Nconstant
Jump to page Nyesno (next/previous only)
Stable while data changesrows shift between pagesstable: continues after the last seen id
Needs a unique sort keyyes, for stabilityyes (_id)
Total count on every pageextra CountDocumentsnot needed (use limit + 1 to know whether there is a next page)
Good forsmall admin tablesfeeds, APIs, exports

The tests confirm that SkipPage(3, 20) sets skip 40 and limit 20, and that After(last, 25) sets no skip, filters {"_id":{"$gt":{"$oid":"65f000000000000000000001"}}} and returns an empty filter for the first page.

Real scenario: an infinite-scroll feed and a public API (next token = last id, range); a back-office table of 300 rows (skip is fine).

Fix / how to use it: default to range pagination; encode the last _id as an opaque token; when the sort is by a non-unique field such as created_at, sort by (created_at, _id) and filter on both.

Update: UpdateOne/UpdateMany, $set, $inc, $push, $addToSet Must-know ​

In plain words: An update is a second document that says what to change. $set writes values, $inc adds a number, $push appends to an array, $addToSet appends only if the value is not already there.

Common misunderstanding: "I read the document, change the struct and save it back, that is an update." Between your read and your write another request can change the same document, and your save erases its change: the lost update. $inc performs the arithmetic on the server, atomically on that document. Also: an update without an operator (a plain document) is rejected by UpdateOne; replacing a document is ReplaceOne.

Definition: coll.UpdateOne(ctx, filter, update, opts...) changes the first match, UpdateMany all matches; both return *UpdateResult{MatchedCount, ModifiedCount, UpsertedCount, UpsertedID}. A filter that matches nothing is not an error: check MatchedCount. Operators: $set, $unset, $inc, $mul, $min, $max, $push, $pull, $addToSet, $currentDate, $setOnInsert.

T1 (read-modify-write)                       T2 (read-modify-write)         document: logins = 5
1  FindOne  → logins 5                       FindOne → logins 5
2  logins = 6                                logins = 6
3  ReplaceOne(logins 6)                      ReplaceOne(logins 6)           → 6, one login lost
--- with $inc ---
1  UpdateOne({$inc: {logins: 1}})            UpdateOne({$inc: {logins: 1}}) → 7, both counted
OperatorEffectGotcha
$setsets the listed fieldscreates missing fields; dotted paths set nested fields
$incadds a numbercreates the field with the value if missing
$pushappends, duplicates allowedthe array grows without bound unless you cap it with $slice
$addToSetappends if absentcompares whole values, so for sub-documents field order matters
$pullremoves matching elementswith conditions, not only values
$setOnInsertapplies only when an upsert insertsignored on updates
$currentDatesets to the server's timeavoids clock skew between app servers

The updates package builds each of these as an ordered bson.D and its tests pin the documents: {"$inc":{"logins":1}}, {"$push":{"notes":"hello"}}, {"$addToSet":{"tags":"go"}}, and {"$set":{"name":"Ada","updated_at":{"$date":"2026-01-02T03:04:05Z"}}}.

go
// Package updates builds update documents, upserts and bulk writes.
package updates

import (
	"time"

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

	"academy/mongodb-with-go/models"
)

// Rename sets two fields in one atomic document update.
func Rename(name string, now time.Time) bson.D {
	return bson.D{{Key: "$set", Value: bson.D{
		{Key: "name", Value: name},
		{Key: "updated_at", Value: now},
	}}}
}

// Inc adds delta to a numeric field atomically on the server. This is the
// fix for the read-modify-write lost update.
func Inc(field string, delta int) bson.D {
	return bson.D{{Key: "$inc", Value: bson.D{{Key: field, Value: delta}}}}
}

// Push appends to an array, duplicates allowed.
func Push(field string, v any) bson.D {
	return bson.D{{Key: "$push", Value: bson.D{{Key: field, Value: v}}}}
}

// AddToSet appends only when the value is not already present.
func AddToSet(field string, v any) bson.D {
	return bson.D{{Key: "$addToSet", Value: bson.D{{Key: field, Value: v}}}}
}

// UpsertByEmail returns the filter, update and options for "create or update
// by natural key". $setOnInsert applies only when the document is created.
func UpsertByEmail(email, name string, now time.Time) (bson.D, bson.D, *options.UpdateOneOptionsBuilder) {
	filter := bson.D{{Key: "email", Value: email}}
	update := bson.D{
		{Key: "$set", Value: bson.D{{Key: "name", Value: name}, {Key: "updated_at", Value: now}}},
		{Key: "$setOnInsert", Value: bson.D{{Key: "created_at", Value: now}}},
	}
	return filter, update, options.UpdateOne().SetUpsert(true)
}

// Counter increments a counter and returns the new value in one round trip:
// FindOneAndUpdate with ReturnDocument After.
func Counter(name string) (bson.D, bson.D, *options.FindOneAndUpdateOptionsBuilder) {
	return bson.D{{Key: "_id", Value: name}},
		Inc("seq", 1),
		options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)
}

// SyncModels turns a batch of users into one unordered BulkWrite: replace by
// email with upsert. One round trip, partial failure reported per model.
func SyncModels(users []models.User) []mongo.WriteModel {
	out := make([]mongo.WriteModel, 0, len(users))
	for _, u := range users {
		out = append(out, mongo.NewReplaceOneModel().
			SetFilter(bson.D{{Key: "email", Value: u.Email}}).
			SetReplacement(u).
			SetUpsert(true))
	}
	return out
}

// Unordered keeps going after the first failing model.
func Unordered() *options.BulkWriteOptionsBuilder {
	return options.BulkWrite().SetOrdered(false)
}
go
package updates

import (
	"testing"
	"time"

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

	"academy/mongodb-with-go/models"
)

func ext(t *testing.T, v any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(v, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestOperators(t *testing.T) {
	now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	cases := []struct {
		name string
		got  any
		want string
	}{
		{"set", Rename("Ada", now), `{"$set":{"name":"Ada","updated_at":{"$date":"2026-01-02T03:04:05Z"}}}`},
		{"inc", Inc("logins", 1), `{"$inc":{"logins":1}}`},
		{"push", Push("notes", "hello"), `{"$push":{"notes":"hello"}}`},
		{"addToSet", AddToSet("tags", "go"), `{"$addToSet":{"tags":"go"}}`},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := ext(t, c.got); got != c.want {
				t.Fatalf("got  %s\nwant %s", got, c.want)
			}
		})
	}
}

func TestUpsertUsesSetOnInsert(t *testing.T) {
	now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	f, u, o := UpsertByEmail("a@example.test", "Ada", now)
	if ext(t, f) != `{"email":"a@example.test"}` {
		t.Fatalf("filter %s", ext(t, f))
	}
	raw := bson.Raw(mustMarshal(t, u))
	if _, err := raw.LookupErr("$setOnInsert", "created_at"); err != nil {
		t.Fatal("created_at must live under $setOnInsert so updates do not overwrite it")
	}
	opts := o.List()
	if len(opts) != 1 {
		t.Fatalf("expected one option setter, got %d", len(opts))
	}
}

func mustMarshal(t *testing.T, v any) []byte {
	t.Helper()
	b, err := bson.Marshal(v)
	if err != nil {
		t.Fatal(err)
	}
	return b
}

func TestSyncModels(t *testing.T) {
	users := []models.User{
		models.New("a@example.test", "Ada", time.Now()),
		models.New("b@example.test", "Bob", time.Now()),
	}
	ms := SyncModels(users)
	if len(ms) != 2 {
		t.Fatalf("got %d models, want 2", len(ms))
	}
	for _, m := range ms {
		if _, ok := m.(*mongo.ReplaceOneModel); !ok {
			t.Fatalf("unexpected model type %T", m)
		}
	}
	bo := &options.BulkWriteOptions{}
	for _, set := range Unordered().List() {
		if err := set(bo); err != nil {
			t.Fatal(err)
		}
	}
	if bo.Ordered == nil || *bo.Ordered {
		t.Fatal("Unordered must end with Ordered=false (the builder starts at true)")
	}
}

func TestCounterReturnsAfter(t *testing.T) {
	f, u, o := Counter("invoice")
	if ext(t, f) != `{"_id":"invoice"}` || ext(t, u) != `{"$inc":{"seq":1}}` {
		t.Fatalf("unexpected %s %s", ext(t, f), ext(t, u))
	}
	if len(o.List()) != 2 {
		t.Fatalf("expected upsert and returnDocument setters, got %d", len(o.List()))
	}
}

Real scenario: a like counter and a wallet balance ($inc, ideally with a guard such as balance >= amount in the filter); a tag list ($addToSet); an activity log capped at 100 entries ($push with $each and $slice); a "touch" of updated_at.

Fix / how to use it: express the change as an operator; put the safety condition in the filter ({ _id: id, balance: { $gte: 100 } } and check MatchedCount == 1), which is the atomic form of check-then-write. See Optimistic vs Pessimistic Locking for the version-field variant.

Upsert, ReplaceOne, FindOneAndUpdate Important ​

In plain words: An upsert says "update it if it exists, create it if not". ReplaceOne swaps the whole document. FindOneAndUpdate changes a document and hands you back the old or new version in one step.

Common misunderstanding: "An upsert on a non-unique filter is safe." Two concurrent upserts with the same filter can both insert unless a unique index covers the filter fields; the loser then fails with code 11000 and should retry as an update. Also, ReplaceOne removes every field the new document lacks, including ones another writer just added.

Definition: options.UpdateOne().SetUpsert(true) makes UpdateOne insert when nothing matches, using the filter's equality fields as a base; $setOnInsert carries the values only used on insert (the snippet puts created_at there so later updates do not overwrite it). coll.ReplaceOne(ctx, filter, replacement) replaces the first match, keeping _id. coll.FindOneAndUpdate(ctx, filter, update, options.FindOneAndUpdate().SetReturnDocument(options.After)) returns the document after the change (the default is before); there are FindOneAndReplace and FindOneAndDelete too, all returning a *SingleResult that reports ErrNoDocuments on a miss unless upserting.

OperationReturnsAtomic on one documentUse for
UpdateOne + SetUpsert(true)UpsertedID when it insertedyescreate-or-update by natural key
ReplaceOnecountsyesfull-document save (back-office edit)
FindOneAndUpdate + Afterthe new documentyescounters, state transitions, "claim a job"
FindOneAndDeletethe removed documentyespop from a queue collection

The snippet's Counter builds the sequence-counter form: filter {"_id":"invoice"}, update {"$inc":{"seq":1}}, options upsert plus ReturnDocument(After).

Real scenario: a sync job that upserts customers by email; an invoice-number counter; a job queue where a worker claims one pending job by FindOneAndUpdate({status:"pending"}, {$set:{status:"running"}}).

Fix / how to use it: pair every upsert with a unique index on the filter fields and handle 11000 by retrying once; use FindOneAndUpdate when you need the resulting value, not a second FindOne.

Delete: DeleteOne, DeleteMany Important ​

In plain words: Remove the first match, or every match. Nothing is asked twice.

Common misunderstanding: "DeleteOne with an empty filter deletes nothing unless I am sure." It deletes the first document it finds. An empty filter in DeleteMany removes the whole collection's documents (the indexes stay). Both report DeletedCount and neither errors on zero.

Definition: coll.DeleteOne(ctx, filter) and coll.DeleteMany(ctx, filter) return *DeleteResult{DeletedCount}. For "soft delete" you $set a deleted_at instead and filter it out in reads.

Real scenario: delete a draft by id; purge test data; GDPR erasure by user_id (DeleteMany); expire old rows (prefer a TTL index, see Indexes).

Fix / how to use it: build the filter from a typed id, never from a map; treat DeletedCount == 0 as "not found" for single deletes (the repository does); log the count for DeleteMany.

Bulk write Important ​

In plain words: A bulk write sends many different writes (inserts, updates, replaces, deletes) in as few requests as the batch limit allows and reports a summary.

Common misunderstanding: "A bulk write is a transaction." It is one request for up to 100,000 writes: the manual says "a maximum of 100,000 writes in a single batch operation" and that above that "the client driver divides the batch into smaller groups". With the default ordered mode the server stops at the first failing model, and everything before it stays applied. With SetOrdered(false) it continues and collects errors in a mongo.BulkWriteException.

Definition: coll.BulkWrite(ctx, []mongo.WriteModel{...}, options.BulkWrite().SetOrdered(false)). Models: mongo.NewInsertOneModel(), NewUpdateOneModel(), NewUpdateManyModel(), NewReplaceOneModel(), NewDeleteOneModel(), NewDeleteManyModel(), each with chained setters (SetFilter, SetUpdate, SetReplacement, SetUpsert). The builder starts with ordered=true, so Unordered() in the snippet appends a setter and the test applies the setters to read the final value.

Real scenario: syncing 10,000 customers from a CRM (one ReplaceOne with upsert per row, unordered, chunks of 1,000); applying a day of events; cleaning up after a job.

Fix / how to use it: chunk the input; use unordered when the writes are independent; read BulkWriteException.WriteErrors for the failing indices; mongo.IsDuplicateKeyError returns true "if at least one of the errors is a duplicate key error".

Indexes: CreateOne, unique, compound, TTL, text Must-know ​

In plain words: An index is a sorted side structure that lets the server find documents without reading the whole collection. Without an index on the field you filter or sort by, every query is a full collection scan.

Common misunderstanding: "MongoDB indexes everything." Only _id is indexed by default. Every other field you filter, sort or join on needs its own index, and every index slows writes a little and uses memory. Also, a unique index, not a FindOne before the insert, is what really prevents duplicates.

Definition: coll.Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{...}, Options: options.Index()...}) creates one index; CreateMany creates several. Keys must be an ordered bson.D (the driver comment on IndexModel.Keys says "Map types such as bson.M are not valid"). Creating an identical index again is a no-op; a different definition under the same name fails with IndexOptionsConflict (code 85) or IndexKeySpecsConflict (code 86).

IndexGoPurposeNotes
single fieldKeys: bson.D{{Key: "email", Value: 1}}equality and range on one fielddirection matters only for sorts on several fields
uniqueoptions.Index().SetUnique(true)one document per keythe database enforces it; violations are code 11000
compoundkeys customer_id, status, created_atfilter on a prefix, then sortkey order is the design: equality fields first, then sort, then range
TTLSetExpireAfterSeconds(0) on a date fielddelete documents after a timea background task removes them about every 60 seconds, so deletion is not instant
textKeys: name: "text", bio: "text" + SetWeightsword search with stemmingone text index per collection
partialSetPartialFilterExpression(status: "unpaid")index only some documentssmaller and faster, used only when the query implies the filter
multikeyautomatic on an array fieldmatch array elementsone entry per element; a compound index may hold at most one array field

The TTL manual page says "A background thread in mongod reads the values in the index and removes expired documents from the collection" and that the task "runs every 60 seconds". A TTL index on expires_at with ExpireAfterSeconds(0) removes a document once its own expires_at has passed, which is how you expire sessions with per-document lifetimes.

Query: { customer_id: X, status: "paid" } sort { created_at: -1 }
Index: { customer_id: 1, status: 1, created_at: -1 }
1  descend to customer_id = X            (equality)
2  descend to status = "paid"            (equality)
3  walk entries already ordered by created_at descending   (sort needs no extra step)
go
// Package indexes declares the indexes of the users, sessions and orders
// collections and creates them at start-up.
package indexes

import (
	"context"

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

// Users returns the indexes of the users collection.
func Users() []mongo.IndexModel {
	return []mongo.IndexModel{
		{ // unique: the database, not the application, enforces one account per email
			Keys:    bson.D{{Key: "email", Value: 1}},
			Options: options.Index().SetUnique(true).SetName("email_unique"),
		},
		{ // text: one text index per collection, weights rank name above bio
			Keys: bson.D{{Key: "name", Value: "text"}, {Key: "bio", Value: "text"}},
			Options: options.Index().SetName("name_bio_text").
				SetWeights(bson.D{{Key: "name", Value: 5}, {Key: "bio", Value: 1}}),
		},
	}
}

// Orders returns a compound index. Key order matters: equality first, then
// sort, then range (the ESR rule).
func Orders() []mongo.IndexModel {
	return []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "customer_id", Value: 1}, {Key: "status", Value: 1}, {Key: "created_at", Value: -1}},
			Options: options.Index().SetName("customer_status_created"),
		},
		{ // partial: only unpaid orders are indexed, so the index stays small
			Keys: bson.D{{Key: "created_at", Value: 1}},
			Options: options.Index().SetName("unpaid_created").
				SetPartialFilterExpression(bson.D{{Key: "status", Value: "unpaid"}}),
		},
	}
}

// Sessions returns a TTL index: the server deletes a document once the time
// in expires_at has passed (the cleaner runs about once a minute).
func Sessions() []mongo.IndexModel {
	return []mongo.IndexModel{{
		Keys:    bson.D{{Key: "expires_at", Value: 1}},
		Options: options.Index().SetName("expires_ttl").SetExpireAfterSeconds(0),
	}}
}

// Ensure creates the indexes. CreateMany is idempotent for identical
// definitions and fails with an IndexOptionsConflict (code 85) or
// IndexKeySpecsConflict (86) for a different definition under the same name.
func Ensure(ctx context.Context, c *mongo.Collection, models []mongo.IndexModel) ([]string, error) {
	return c.Indexes().CreateMany(ctx, models)
}

// Resolve applies the setters of an index options builder to a plain struct.
func Resolve(m mongo.IndexModel) (*options.IndexOptions, error) {
	o := &options.IndexOptions{}
	if m.Options == nil {
		return o, nil
	}
	for _, set := range m.Options.List() {
		if err := set(o); err != nil {
			return nil, err
		}
	}
	return o, nil
}

The tests read the options back and assert: the email index is unique and named email_unique; the text index has weights {"name":5,"bio":1}; the compound keys keep the order {"customer_id":1,"status":1,"created_at":-1}; the partial filter is {"status":"unpaid"}; the TTL value is 0; and every key document is a bson.D.

go
package indexes

import (
	"testing"

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

func keys(t *testing.T, k any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(k, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestUniqueEmail(t *testing.T) {
	m := Users()[0]
	o, err := Resolve(m)
	if err != nil {
		t.Fatal(err)
	}
	if o.Unique == nil || !*o.Unique || *o.Name != "email_unique" {
		t.Fatalf("unexpected options %+v", o)
	}
	if keys(t, m.Keys) != `{"email":1}` {
		t.Fatalf("keys %s", keys(t, m.Keys))
	}
}

func TestTextIndexHasWeights(t *testing.T) {
	m := Users()[1]
	if keys(t, m.Keys) != `{"name":"text","bio":"text"}` {
		t.Fatalf("keys %s", keys(t, m.Keys))
	}
	o, _ := Resolve(m)
	if keys(t, o.Weights) != `{"name":5,"bio":1}` {
		t.Fatalf("weights %s", keys(t, o.Weights))
	}
}

func TestCompoundKeyOrder(t *testing.T) {
	m := Orders()[0]
	if got := keys(t, m.Keys); got != `{"customer_id":1,"status":1,"created_at":-1}` {
		t.Fatalf("key order must be preserved, got %s", got)
	}
}

func TestPartialFilter(t *testing.T) {
	o, _ := Resolve(Orders()[1])
	if keys(t, o.PartialFilterExpression) != `{"status":"unpaid"}` {
		t.Fatalf("partial filter %s", keys(t, o.PartialFilterExpression))
	}
}

func TestTTL(t *testing.T) {
	o, _ := Resolve(Sessions()[0])
	if o.ExpireAfterSeconds == nil || *o.ExpireAfterSeconds != 0 {
		t.Fatalf("expected expireAfterSeconds 0, got %+v", o.ExpireAfterSeconds)
	}
}

// A bson.M is rejected as index keys by the driver docs: key order defines the
// index. The test documents the rule instead of calling a server.
func TestKeysAreOrderedDocuments(t *testing.T) {
	for _, m := range append(Users(), Orders()...) {
		if _, ok := m.Keys.(bson.D); !ok {
			t.Fatalf("index keys must be bson.D, got %T", m.Keys)
		}
	}
}

Real scenario: unique email; compound (customer_id, status, created_at) for an order history screen; TTL for sessions and password reset tokens; a text index for a search box; a partial index for the 2% of orders that are unpaid.

Fix / how to use it: create indexes at start-up or in a migration job, not inside request handlers; check the plan with explain in the shell when a query is slow (see Query Planning, EXPLAIN & Join Algorithms for the general method and Indexing for index design). Creating an index on a large collection is heavy: do it deliberately, outside peak hours.

Aggregation pipeline: $match, $group, $lookup, $unwind, $project Must-know ​

In plain words: An aggregation pipeline is a list of stages. Documents flow through the stages in order: filter, group, reshape, join, sort. It is MongoDB's way to answer "total revenue per customer".

Common misunderstanding: "Aggregation is for reports only, and the order of stages does not matter." The order is the performance: a $match first can use an index and shrinks everything after it; a $match after a $group reads the whole collection. And the pipeline must be an ordered array of stage documents, never a map.

Definition: coll.Aggregate(ctx, pipeline, opts...) returns a cursor; mongo.Pipeline is []bson.D, one bson.D per stage, each with one key ($match, $group, $sort, $limit, $unwind, $project, $lookup...). Read results with All or Next/Decode into a result struct (pipelines.Row in the snippet).

StageWhat it doesSQL ideaNote
$matchfilters documentsWHEREfirst, so it can use an index
$groupgroups by _id and aggregates ($sum, $avg, $push)GROUP BY_id is the group key
$sort, $limitorder and cutORDER BY, LIMIT$sort + $limit is optimised into a top-N
$unwindone output document per array elementlateral join on an arraypreserveNullAndEmptyArrays keeps empty ones
$projectinclude, exclude or compute fieldsSELECT listcan rename (sku: "$_id")
$lookupjoins another collectionleft outer JOINresult is an array in as; needs an index on the foreign field
go
// Package pipelines builds aggregation pipelines.
package pipelines

import (
	"time"

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

// RevenueByCustomer filters early with $match (so an index can be used),
// then groups and sorts.
func RevenueByCustomer(since time.Time) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$match", Value: bson.D{
			{Key: "status", Value: "paid"},
			{Key: "created_at", Value: bson.D{{Key: "$gte", Value: since}}},
		}}},
		{{Key: "$group", Value: bson.D{
			{Key: "_id", Value: "$customer_id"},
			{Key: "revenue", Value: bson.D{{Key: "$sum", Value: "$total"}}},
			{Key: "orders", Value: bson.D{{Key: "$sum", Value: 1}}},
		}}},
		{{Key: "$sort", Value: bson.D{{Key: "revenue", Value: -1}}}},
		{{Key: "$limit", Value: 10}},
	}
}

// TopSKUs unwinds the embedded items array so each line becomes a document.
func TopSKUs() mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$unwind", Value: "$items"}},
		{{Key: "$group", Value: bson.D{
			{Key: "_id", Value: "$items.sku"},
			{Key: "units", Value: bson.D{{Key: "$sum", Value: "$items.qty"}}},
		}}},
		{{Key: "$project", Value: bson.D{
			{Key: "_id", Value: 0},
			{Key: "sku", Value: "$_id"},
			{Key: "units", Value: 1},
		}}},
		{{Key: "$sort", Value: bson.D{{Key: "units", Value: -1}}}},
	}
}

// Row is the shape of one TopSKUs result.
type Row struct {
	SKU   string `bson:"sku"`
	Units int64  `bson:"units"`
}

The pipeline test asserts the stage names in order ($match,$group,$sort,$limit) and the complete serialised pipeline of TopSKUs: $unwind of $items, $group by $items.sku summing $items.qty, $project renaming _id to sku, $sort by units.

go
package pipelines

import (
	"strings"
	"testing"
	"time"

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

func TestStageOrder(t *testing.T) {
	p := RevenueByCustomer(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
	var names []string
	for _, stage := range p {
		names = append(names, stage[0].Key)
	}
	if got := strings.Join(names, ","); got != "$match,$group,$sort,$limit" {
		t.Fatalf("stages = %s", got)
	}
}

func TestPipelineSerialisesAsArray(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"pipeline": TopSKUs()}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"pipeline":[{"$unwind":"$items"},{"$group":{"_id":"$items.sku","units":{"$sum":"$items.qty"}}},` +
		`{"$project":{"_id":0,"sku":"$_id","units":1}},{"$sort":{"units":-1}}]}`
	if string(b) != want {
		t.Fatalf("got  %s\nwant %s", b, want)
	}
}

Real scenario: revenue per customer in the last 30 days; top-selling SKUs from embedded order lines ($unwind then $group); an order page that joins the customer ($lookup).

Fix / how to use it: build pipelines in functions that return mongo.Pipeline and test their serialised form; keep $match first; add allowDiskUse only for known big groups; for reports on huge data consider a pre-aggregated collection (see OLTP vs OLAP & Columnar Storage).

Typed filters with generics Important ​

In plain words: A field wrapper that knows its value type lets the compiler reject Age.Eq("ten"). You declare each field once, and filters are built from those declarations.

Common misunderstanding: "Generics will make the driver type-safe." They cannot see inside a string key: nothing checks that "age" is the stored name. The wrapper moves that check to one place (the declaration) and a test; it does not remove it.

Definition: type Field[V any] struct{ name string } with methods Eq, Ne, Gt, Gte, Lt, In(vs ...V) and Exists, each returning an ordered bson.D; typed.And and typed.Or combine clauses. Generic type parameters arrived in Go 1.18 (see Generics). Declare fields as package-level variables: var Age = typed.F[int]("age").

go
// Package typed makes filter values type-checked at compile time with generics.
package typed

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

// Field is a document field whose values have type V.
type Field[V any] struct{ name string }

// F declares a field. Declare each field once, as a package-level variable.
func F[V any](name string) Field[V] { return Field[V]{name: name} }

// Name returns the dotted path of the field.
func (f Field[V]) Name() string { return f.name }

func (f Field[V]) op(op string, v any) bson.D {
	return bson.D{{Key: f.name, Value: bson.D{{Key: op, Value: v}}}}
}

// Eq matches equal values.
func (f Field[V]) Eq(v V) bson.D { return f.op("$eq", v) }

// Ne matches different values.
func (f Field[V]) Ne(v V) bson.D { return f.op("$ne", v) }

// Gt matches greater values.
func (f Field[V]) Gt(v V) bson.D { return f.op("$gt", v) }

// Gte matches greater or equal values.
func (f Field[V]) Gte(v V) bson.D { return f.op("$gte", v) }

// Lt matches smaller values.
func (f Field[V]) Lt(v V) bson.D { return f.op("$lt", v) }

// In matches any of the values. With no values the filter matches nothing: a
// nil slice would encode as null, so it is replaced by an empty array.
func (f Field[V]) In(vs ...V) bson.D {
	if vs == nil {
		vs = []V{}
	}
	return f.op("$in", vs)
}

// Exists matches documents that have (or lack) the field.
func (f Field[V]) Exists(yes bool) bson.D { return f.op("$exists", yes) }

// And joins clauses with $and.
func And(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$and", Value: arr}}
}

// Or joins clauses with $or.
func Or(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$or", Value: arr}}
}
go
package typed

import (
	"testing"
	"time"

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

var (
	Email     = F[string]("email")
	Age       = F[int]("age")
	CreatedAt = F[time.Time]("created_at")
)

func ext(t *testing.T, v any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(v, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestTypedFilters(t *testing.T) {
	f := And(Email.Eq("a@example.test"), Age.Gte(18), Age.In(18, 21, 30))
	want := `{"$and":[{"email":{"$eq":"a@example.test"}},{"age":{"$gte":18}},{"age":{"$in":[18,21,30]}}]}`
	if got := ext(t, f); got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

func TestTimeValuesBecomeDates(t *testing.T) {
	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	got := ext(t, CreatedAt.Lt(at))
	want := `{"created_at":{"$lt":{"$date":"2026-01-02T03:04:05Z"}}}`
	if got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

func TestOr(t *testing.T) {
	got := ext(t, Or(Age.Lt(18), Email.Exists(false)))
	want := `{"$or":[{"age":{"$lt":18}},{"email":{"$exists":false}}]}`
	if got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

// Age.Eq("x") does not compile: the compiler rejects a string for Field[int].
func TestNameKeepsDottedPath(t *testing.T) {
	if F[string]("address.city").Name() != "address.city" {
		t.Fatal("dotted paths are kept as is")
	}
}

func TestEmptyInIsEmptyArray(t *testing.T) {
	want := `{"age":{"$in":[]}}`
	if got := ext(t, Age.In()); got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

The tests pin {"$and":[{"email":{"$eq":"a@example.test"}},{"age":{"$gte":18}},{"age":{"$in":[18,21,30]}}]} and show that a time.Time value becomes a BSON date ({"created_at":{"$lt":{"$date":"2026-01-02T03:04:05Z"}}}).

Real scenario: a service where product, order and user filters are built in twenty places; a code review that no longer has to check operator spelling.

Fix / how to use it: keep one fields.go per document type with the typed declarations next to the struct; add a test that marshals a sample struct and checks that each declared name is a key of the result, so a renamed tag fails a test and not production.

Generic repository: Repository[T] Must-know ​

In plain words: One small type, Repository[T], that knows how to insert, get, list, update, delete and count documents of any type T, so you write the error handling once.

Common misunderstanding: "A generic repository hides MongoDB, so I can switch databases." It hides driver types and errors, not the model: a bson.D filter in its signature is MongoDB. Its job is consistent error mapping, cursor hygiene and a test seam. It is also not an ORM: no change tracking, no lazy loading.

Definition: the repository depends on a narrow Collection interface with InsertOne, FindOne, Find, UpdateOne, DeleteOne and CountDocuments, whose signatures match *mongo.Collection exactly (a compile-time assertion var _ Collection = (*mongo.Collection)(nil) proves it). Get does the "Decode into T" step: var out T; FindOne(...).Decode(&out); List uses Cursor.All into []T; Each uses Next and Decode. mapErr turns mongo.ErrNoDocuments into ErrNotFound and a duplicate key into ErrConflict, wrapping with %w: %w so the original error stays in the chain (multiple %w verbs need Go 1.20 or newer).

caller                         Repository[User]                    Collection
1  Get(ctx, filter) ─────────▶ var out User; FindOne(ctx, filter) ─▶ SingleResult
2                              Decode(&out) fills out
3                              err == mongo.ErrNoDocuments ?
4  ◀──────── ErrNotFound (wraps the driver error) ── yes
5  ◀──────── &out ───────────────────────────────────────────────── no
go
// Package repo is a small generic repository over a MongoDB collection.
// It depends on the Collection interface, which *mongo.Collection satisfies,
// so the logic can be tested without a server.
package repo

import (
	"context"
	"errors"
	"fmt"

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

// Domain errors: callers match these, never driver errors.
var (
	ErrNotFound = errors.New("repo: not found")
	ErrConflict = errors.New("repo: duplicate key")
)

// Collection is the subset of *mongo.Collection the repository uses.
type Collection interface {
	InsertOne(ctx context.Context, document any, opts ...options.Lister[options.InsertOneOptions]) (*mongo.InsertOneResult, error)
	FindOne(ctx context.Context, filter any, opts ...options.Lister[options.FindOneOptions]) *mongo.SingleResult
	Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*mongo.Cursor, error)
	UpdateOne(ctx context.Context, filter any, update any, opts ...options.Lister[options.UpdateOneOptions]) (*mongo.UpdateResult, error)
	DeleteOne(ctx context.Context, filter any, opts ...options.Lister[options.DeleteOneOptions]) (*mongo.DeleteResult, error)
	CountDocuments(ctx context.Context, filter any, opts ...options.Lister[options.CountOptions]) (int64, error)
}

var _ Collection = (*mongo.Collection)(nil)

// Repository stores documents of type T.
type Repository[T any] struct {
	coll Collection
}

// New wraps a collection.
func New[T any](c Collection) *Repository[T] { return &Repository[T]{coll: c} }

// Insert stores doc and returns the generated _id.
func (r *Repository[T]) Insert(ctx context.Context, doc *T) (bson.ObjectID, error) {
	res, err := r.coll.InsertOne(ctx, doc)
	if err != nil {
		return bson.ObjectID{}, mapErr(err)
	}
	id, ok := res.InsertedID.(bson.ObjectID)
	if !ok {
		return bson.ObjectID{}, fmt.Errorf("repo: _id is %T, not ObjectID", res.InsertedID)
	}
	return id, nil
}

// Get returns the first document that matches. Decode into T is the generic
// step: the driver fills a fresh T for every call.
func (r *Repository[T]) Get(ctx context.Context, filter bson.D) (*T, error) {
	var out T
	if err := r.coll.FindOne(ctx, filter).Decode(&out); err != nil {
		return nil, mapErr(err)
	}
	return &out, nil
}

// List reads every match into memory with Cursor.All. Cap it with Limit.
func (r *Repository[T]) List(ctx context.Context, filter bson.D, opts ...options.Lister[options.FindOptions]) ([]T, error) {
	cur, err := r.coll.Find(ctx, filter, opts...)
	if err != nil {
		return nil, mapErr(err)
	}
	defer cur.Close(ctx)
	var out []T
	if err := cur.All(ctx, &out); err != nil {
		return nil, mapErr(err)
	}
	return out, nil
}

// Each streams matches one by one with Next and Decode, so memory stays flat.
func (r *Repository[T]) Each(ctx context.Context, filter bson.D, fn func(T) error, opts ...options.Lister[options.FindOptions]) error {
	cur, err := r.coll.Find(ctx, filter, opts...)
	if err != nil {
		return mapErr(err)
	}
	defer cur.Close(ctx)
	for cur.Next(ctx) {
		var item T
		if err := cur.Decode(&item); err != nil {
			return mapErr(err)
		}
		if err := fn(item); err != nil {
			return err
		}
	}
	return mapErr(cur.Err())
}

// Update applies an update document to the first match. A match count of zero
// is ErrNotFound, not success.
func (r *Repository[T]) Update(ctx context.Context, filter, update bson.D) error {
	res, err := r.coll.UpdateOne(ctx, filter, update)
	if err != nil {
		return mapErr(err)
	}
	if res.MatchedCount == 0 {
		return ErrNotFound
	}
	return nil
}

// Delete removes the first match; zero deleted is ErrNotFound.
func (r *Repository[T]) Delete(ctx context.Context, filter bson.D) error {
	res, err := r.coll.DeleteOne(ctx, filter)
	if err != nil {
		return mapErr(err)
	}
	if res.DeletedCount == 0 {
		return ErrNotFound
	}
	return nil
}

// Count returns the exact number of matches.
func (r *Repository[T]) Count(ctx context.Context, filter bson.D) (int64, error) {
	n, err := r.coll.CountDocuments(ctx, filter)
	return n, mapErr(err)
}

// mapErr turns driver errors into domain errors and keeps the original
// error in the chain for logging.
func mapErr(err error) error {
	switch {
	case err == nil:
		return nil
	case errors.Is(err, mongo.ErrNoDocuments):
		return fmt.Errorf("%w: %w", ErrNotFound, err)
	case mongo.IsDuplicateKeyError(err):
		return fmt.Errorf("%w: %w", ErrConflict, err)
	default:
		return err
	}
}

The test double is where the design pays: the fake implements Collection and returns results built with the driver's own mongo.NewSingleResultFromDocument and mongo.NewCursorFromDocuments, so BSON decoding is real while no server runs. The tests cover decode into T, ErrNoDocuments to ErrNotFound (with the driver error still reachable through errors.Is), a constructed mongo.WriteException with code 11000 to ErrConflict (with mongo.IsDuplicateKeyError still true through the wrap), List and Each, update and delete reporting a miss, and the same repository used for a second type.

go
package repo

import (
	"context"
	"errors"
	"testing"
	"time"

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

	"academy/mongodb-with-go/models"
)

// fake implements Collection without a server. Documents come back through
// the driver's own constructors, so Decode and All run the real BSON codecs.
type fake struct {
	docs      []any
	insertErr error
	updated   int64
	deleted   int64
	lastFind  any
}

func (f *fake) InsertOne(_ context.Context, doc any, _ ...options.Lister[options.InsertOneOptions]) (*mongo.InsertOneResult, error) {
	if f.insertErr != nil {
		return nil, f.insertErr
	}
	return &mongo.InsertOneResult{InsertedID: bson.NewObjectID()}, nil
}

func (f *fake) FindOne(_ context.Context, filter any, _ ...options.Lister[options.FindOneOptions]) *mongo.SingleResult {
	f.lastFind = filter
	if len(f.docs) == 0 {
		return mongo.NewSingleResultFromDocument(bson.D{}, mongo.ErrNoDocuments, nil)
	}
	return mongo.NewSingleResultFromDocument(f.docs[0], nil, nil)
}

func (f *fake) Find(_ context.Context, filter any, _ ...options.Lister[options.FindOptions]) (*mongo.Cursor, error) {
	f.lastFind = filter
	return mongo.NewCursorFromDocuments(f.docs, nil, nil)
}

func (f *fake) UpdateOne(context.Context, any, any, ...options.Lister[options.UpdateOneOptions]) (*mongo.UpdateResult, error) {
	return &mongo.UpdateResult{MatchedCount: f.updated}, nil
}

func (f *fake) DeleteOne(context.Context, any, ...options.Lister[options.DeleteOneOptions]) (*mongo.DeleteResult, error) {
	return &mongo.DeleteResult{DeletedCount: f.deleted}, nil
}

func (f *fake) CountDocuments(context.Context, any, ...options.Lister[options.CountOptions]) (int64, error) {
	return int64(len(f.docs)), nil
}

func users(n int) []any {
	out := make([]any, n)
	for i := range out {
		u := models.New("u@example.test", "User", time.Now())
		u.ID = bson.NewObjectID()
		out[i] = u
	}
	return out
}

func TestGetDecodesIntoT(t *testing.T) {
	r := New[models.User](&fake{docs: users(1)})
	u, err := r.Get(context.Background(), bson.D{{Key: "email", Value: "u@example.test"}})
	if err != nil {
		t.Fatal(err)
	}
	if u.Email != "u@example.test" || u.ID.IsZero() {
		t.Fatalf("decoded %+v", u)
	}
}

func TestGetMapsNoDocumentsToNotFound(t *testing.T) {
	r := New[models.User](&fake{})
	_, err := r.Get(context.Background(), bson.D{})
	if !errors.Is(err, ErrNotFound) {
		t.Fatalf("want ErrNotFound, got %v", err)
	}
	if !errors.Is(err, mongo.ErrNoDocuments) {
		t.Fatal("the original driver error must stay in the chain")
	}
}

func TestInsertMapsDuplicateKey(t *testing.T) {
	dup := mongo.WriteException{WriteErrors: mongo.WriteErrors{{Code: 11000, Message: "E11000 duplicate key error"}}}
	r := New[models.User](&fake{insertErr: dup})
	u := models.New("a@example.test", "Ada", time.Now())
	_, err := r.Insert(context.Background(), &u)
	if !errors.Is(err, ErrConflict) {
		t.Fatalf("want ErrConflict, got %v", err)
	}
	if !mongo.IsDuplicateKeyError(err) {
		t.Fatal("IsDuplicateKeyError must still work through the wrap")
	}
}

func TestInsertReturnsObjectID(t *testing.T) {
	r := New[models.User](&fake{})
	u := models.New("a@example.test", "Ada", time.Now())
	id, err := r.Insert(context.Background(), &u)
	if err != nil || id.IsZero() {
		t.Fatalf("id=%v err=%v", id, err)
	}
}

func TestListAndEach(t *testing.T) {
	r := New[models.User](&fake{docs: users(3)})
	all, err := r.List(context.Background(), bson.D{})
	if err != nil || len(all) != 3 {
		t.Fatalf("List: %d docs, err %v", len(all), err)
	}
	n := 0
	err = r.Each(context.Background(), bson.D{}, func(models.User) error { n++; return nil })
	if err != nil || n != 3 {
		t.Fatalf("Each visited %d, err %v", n, err)
	}
	stop := errors.New("stop")
	err = r.Each(context.Background(), bson.D{}, func(models.User) error { return stop })
	if !errors.Is(err, stop) {
		t.Fatalf("callback error must be returned, got %v", err)
	}
}

func TestUpdateAndDeleteReportMissing(t *testing.T) {
	r := New[models.User](&fake{})
	if err := r.Update(context.Background(), bson.D{}, bson.D{}); !errors.Is(err, ErrNotFound) {
		t.Fatalf("update: %v", err)
	}
	if err := r.Delete(context.Background(), bson.D{}); !errors.Is(err, ErrNotFound) {
		t.Fatalf("delete: %v", err)
	}
	r = New[models.User](&fake{updated: 1, deleted: 1})
	if err := r.Update(context.Background(), bson.D{}, bson.D{}); err != nil {
		t.Fatal(err)
	}
	if err := r.Delete(context.Background(), bson.D{}); err != nil {
		t.Fatal(err)
	}
}

func TestCount(t *testing.T) {
	r := New[models.User](&fake{docs: users(2)})
	n, err := r.Count(context.Background(), bson.D{})
	if err != nil || n != 2 {
		t.Fatalf("count %d err %v", n, err)
	}
}

// The repository is generic: the same code works for any document type.
func TestSameRepositoryForAnotherType(t *testing.T) {
	type note struct {
		ID   bson.ObjectID `bson:"_id"`
		Text string        `bson:"text"`
	}
	r := New[note](&fake{docs: []any{note{ID: bson.NewObjectID(), Text: "hi"}}})
	got, err := r.Get(context.Background(), bson.D{})
	if err != nil || got.Text != "hi" {
		t.Fatalf("got %+v err %v", got, err)
	}
}
One interface, two implementationsHTTP handlerServiceRepository of TDecode into T, map errorsCollection interfaceFindOne, Find, InsertOne ...mongo.Collectionproduction, needs mongodfaketests1 The repository imports no server code: it only needs the six methods in the interface.2 The fake builds results with mongo.NewCursorFromDocuments, so BSON decoding is the real one.3 Behaviour only a server can show (indexes, transactions) stays in integration tests.

Real scenario: ten collections, one repository type; a service layer that depends on a UserStore interface satisfied by *Repository[User]; a handler test that injects a fake store (see Mocking with Interfaces).

Fix / how to use it: keep it thin (no query builder inside), add collection-specific methods (FindByEmail) in a wrapper that embeds *Repository[User], and keep transactions outside the repository: a transaction spans several repositories, so it is started by the service layer (see Transactions).

Relationships: embedding vs referencing, $lookup, denormalization Must-know ​

In plain words: In SQL a one-to-many relationship is two tables and a join. In MongoDB you choose: put the children inside the parent document (embed), or give the child the parent's id (reference) and join when needed.

Common misunderstanding: "Embedding is the MongoDB way, so I embed everything." Embedded arrays that grow without bound hit the 16 MiB document limit ("Documents in MongoDB must be smaller than 16 mebibytes"), make every update rewrite a large document and cannot be paged. "MongoDB has no joins, so I never reference" is equally wrong: $lookup exists, and many-to-many data belongs in separate collections.

Definition: the manual's guidance: use embedded data for "contains" relationships and one-to-many relationships where the child is viewed in the context of its parent; use references when embedding "would result in duplication of data" that "frequently changes", for "complex many-to-many relationships", or when you "frequently query the related entity on its own". Embedding is also called denormalization (the manual calls embedded models "often considered denormalized because frequently-accessed data is duplicated"); referencing yields normalised data. A snapshot (a copy of the customer's name inside the order) is denormalisation with a purpose: the order should show the name as it was at purchase time.

DecisionEmbedReferenceSnapshot copy
Read together almost alwaysbest: one readtwo reads or $lookupbest
Child countbounded (tens)unboundedn/a
Child changes often, shared by many parentsbad (many rewrites)beststale unless you rewrite copies
Atomic update of parent and childone document, atomicneeds a transactionone document
Query the child on its ownawkward ($unwind)naturalno
Document growthrisk of 16 MiB limitnonesmall

The snippet models an Order that embeds Items, references the customer by customer_id and keeps a customer.name snapshot. Its test proves the order is one document with an items array of two elements, that the customer is a BSON ObjectID reference, and that the snapshot name is stored.

go
// Package relations contrasts embedding and referencing and shows $lookup and
// the cost of denormalisation.
package relations

import (
	"time"

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

// Customer lives in its own collection and is referenced by orders.
type Customer struct {
	ID    bson.ObjectID `bson:"_id,omitempty"`
	Name  string        `bson:"name"`
	Email string        `bson:"email"`
}

// Item is embedded: it has no life outside its order, is read together with
// it, and is bounded (an order has tens of lines, not millions).
type Item struct {
	SKU   string `bson:"sku"`
	Qty   int    `bson:"qty"`
	Price int64  `bson:"price_cents"`
}

// CustomerSnapshot is denormalised: a copy of the fields the order page shows,
// frozen at purchase time. The reference stays for everything else.
type CustomerSnapshot struct {
	Name string `bson:"name"`
}

// Order embeds items, references the customer and snapshots the name.
type Order struct {
	ID         bson.ObjectID    `bson:"_id,omitempty"`
	CustomerID bson.ObjectID    `bson:"customer_id"`
	Customer   CustomerSnapshot `bson:"customer"`
	Items      []Item           `bson:"items"`
	Status     string           `bson:"status"`
	CreatedAt  time.Time        `bson:"created_at"`
}

// WithCustomer joins one order to its customer document. $lookup is a
// left outer join; $unwind turns the one-element array into an object.
func WithCustomer(orderID bson.ObjectID) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$match", Value: bson.D{{Key: "_id", Value: orderID}}}},
		{{Key: "$lookup", Value: bson.D{
			{Key: "from", Value: "customers"},
			{Key: "localField", Value: "customer_id"},
			{Key: "foreignField", Value: "_id"},
			{Key: "as", Value: "customer_doc"},
		}}},
		{{Key: "$unwind", Value: bson.D{
			{Key: "path", Value: "$customer_doc"},
			{Key: "preserveNullAndEmptyArrays", Value: true},
		}}},
		{{Key: "$project", Value: bson.D{
			{Key: "status", Value: 1},
			{Key: "items", Value: 1},
			{Key: "customer_email", Value: "$customer_doc.email"},
		}}},
	}
}

// RecentOrdersPerCustomer is the pipeline form of $lookup: a sub-pipeline with
// let variables, so the joined side can be filtered, sorted and limited.
func RecentOrdersPerCustomer(limit int64) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$lookup", Value: bson.D{
			{Key: "from", Value: "orders"},
			{Key: "let", Value: bson.D{{Key: "cid", Value: "$_id"}}},
			{Key: "pipeline", Value: mongo.Pipeline{
				{{Key: "$match", Value: bson.D{{Key: "$expr", Value: bson.D{
					{Key: "$eq", Value: bson.A{"$customer_id", "$$cid"}},
				}}}}},
				{{Key: "$sort", Value: bson.D{{Key: "created_at", Value: -1}}}},
				{{Key: "$limit", Value: limit}},
			}},
			{Key: "as", Value: "recent_orders"},
		}}},
	}
}

// RenameEverywhere is the price of the snapshot: when a customer changes name
// and you want the snapshot to follow, every order must be rewritten.
func RenameEverywhere(customerID bson.ObjectID, name string) (filter, update bson.D) {
	return bson.D{{Key: "customer_id", Value: customerID}},
		bson.D{{Key: "$set", Value: bson.D{{Key: "customer.name", Value: name}}}}
}

$lookup joins on the server: from (collection), localField, foreignField, as (result array). The test pins the whole pipeline: $match on the order id, $lookup from customers, $unwind with preserveNullAndEmptyArrays: true (so an order without a customer still comes back), $project. A second form uses let and an inner pipeline (the join side can filter, sort and limit: the three most recent orders per customer). The price of the snapshot is RenameEverywhere: one UpdateMany that rewrites every order of the customer when you decide the copy must follow.

go
package relations

import (
	"strings"
	"testing"
	"time"

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

func TestOrderIsOneDocument(t *testing.T) {
	cid := bson.NewObjectID()
	o := Order{
		CustomerID: cid,
		Customer:   CustomerSnapshot{Name: "Ada"},
		Items:      []Item{{SKU: "A", Qty: 1, Price: 500}, {SKU: "B", Qty: 2, Price: 250}},
		Status:     "paid",
		CreatedAt:  time.Now(),
	}
	b, err := bson.Marshal(o)
	if err != nil {
		t.Fatal(err)
	}
	raw := bson.Raw(b)
	items, err := raw.LookupErr("items")
	if err != nil {
		t.Fatal(err)
	}
	vals, _ := items.Array().Values()
	if len(vals) != 2 {
		t.Fatalf("items are embedded in the order, got %d", len(vals))
	}
	ref := raw.Lookup("customer_id")
	if ref.Type != bson.TypeObjectID || ref.ObjectID() != cid {
		t.Fatal("customer is referenced by ObjectID, not embedded")
	}
	if raw.Lookup("customer", "name").StringValue() != "Ada" {
		t.Fatal("snapshot name expected")
	}
}

func TestLookupStages(t *testing.T) {
	id, _ := bson.ObjectIDFromHex("65f000000000000000000001")
	p := WithCustomer(id)
	b, err := bson.MarshalExtJSON(bson.M{"p": p}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"p":[{"$match":{"_id":{"$oid":"65f000000000000000000001"}}},` +
		`{"$lookup":{"from":"customers","localField":"customer_id","foreignField":"_id","as":"customer_doc"}},` +
		`{"$unwind":{"path":"$customer_doc","preserveNullAndEmptyArrays":true}},` +
		`{"$project":{"status":1,"items":1,"customer_email":"$customer_doc.email"}}]}`
	if string(b) != want {
		t.Fatalf("got  %s\nwant %s", b, want)
	}
}

func TestPipelineLookupHasLet(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"p": RecentOrdersPerCustomer(3)}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	for _, frag := range []string{`"let":{"cid":"$_id"}`, `"$$cid"`, `"$limit":3`} {
		if !strings.Contains(string(b), frag) {
			t.Fatalf("missing %s in %s", frag, b)
		}
	}
}

func TestRenameEverywhere(t *testing.T) {
	id, _ := bson.ObjectIDFromHex("65f000000000000000000001")
	f, u := RenameEverywhere(id, "Ada L.")
	fb, _ := bson.MarshalExtJSON(f, false, false)
	ub, _ := bson.MarshalExtJSON(u, false, false)
	if string(fb) != `{"customer_id":{"$oid":"65f000000000000000000001"}}` || string(ub) != `{"$set":{"customer.name":"Ada L."}}` {
		t.Fatalf("%s %s", fb, ub)
	}
}
Embed what is read together, reference what lives on its ownorders (one document)_id, status, created_atitems: [ sku, qty, price_cents ], [ sku, qty, price_cents ]embedded: bounded, read with the order, one atomic writecustomer: name (snapshot copy), customer_id (reference)the copy is fast to read and stale after a renamecustomers (own collection)_id, name, emailqueried on its own,changes often,shared by many orders$lookup1 Embed: contains-relationships, bounded arrays, data always read together. Limit: a document stays under 16 MiB.2 Reference: data that changes often, many-to-many, or queried by itself. Cost: a second query or a $lookup stage.3 Snapshot: copy the few fields a screen needs; decide who updates the copy when the source changes.4 An unbounded array (comments, events) is the classic embedding mistake: move it to its own collection.

For readers coming from SQL, the same order screen in a relational schema is one join; in MongoDB it is one document read, or an aggregation with $lookup:

sql
-- relational: two tables, one join
SELECT o.id, o.status, i.sku, i.qty, c.email
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN customers c   ON c.id = o.customer_id
WHERE o.id = 42;

Real scenario: an order with lines (embed) and a customer (reference plus name snapshot); a blog post with comments (reference when comments are unbounded, embed the last five as a preview); a user with a few addresses (embed).

Fix / how to use it: decide by access pattern, not by habit: what is read together, how large it can grow, how often it changes. For the general design vocabulary see Schema Design, Normalization & Data Types and the document-model discussion in MongoDB in Depth. Index the foreignField of every $lookup.

Transactions: sessions, WithTransaction, replica set requirement Must-know ​

In plain words: A transaction groups several writes so that either all happen or none does. In MongoDB one document is already atomic; you need a transaction only when a change spans documents or collections.

Common misunderstanding: "Transactions work on any MongoDB." The manual says transactions are supported on replica sets and sharded clusters, and the Laravel MongoDB documentation states it plainly: "MongoDB standalone deployments do not support transactions." A single mongod started for development fails; run it as a one-node replica set. Second trap: the callback you give WithTransaction can run more than once.

Definition: session, err := client.StartSession(), defer session.EndSession(ctx), then session.WithTransaction(ctx, fn, opts...). In v2 the callback is func(ctx context.Context) (any, error): the ctx it receives carries the session, and "the SessionContext must be used as the Context parameter for any operations that should be part of the transaction" (the old SessionContext type is gone, the plain ctx plays that role). Errors labelled TransientTransactionError and UnknownTransactionCommitResult "are retried for up to 120 seconds", and the doc comment warns: "The fn callback may be run multiple times during WithTransaction due to retry attempts, so it must be idempotent." Also: "the application MUST NOT silently handle errors within the callback fn": return them, or the driver may retry forever. Transaction options: options.Transaction().SetReadConcern(readconcern.Snapshot()).SetWriteConcern(writeconcern.Majority()).

service                      session / driver                           mongod (replica set)
1  Do(ctx, begin, fn) ──────▶ StartSession
2                             WithTransaction(ctx, callback)
3                             start transaction ───────────────────────▶ snapshot opened
4                             fn(ctx): Debit(ctx) ... Credit(ctx) ─────▶ writes inside the transaction
5                             Credit fails: WriteConflict, label TransientTransactionError
6                             abort, then run fn again (attempt 2) ────▶ new snapshot
7                             commit ──────────────────────────────────▶ visible to others atomically
8  ◀──────────────────────── EndSession, return
go
// Package txn wraps Session.WithTransaction. Transactions need a replica set
// or a sharded cluster; a standalone mongod rejects them.
package txn

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
	"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)

// Session is the part of *mongo.Session the helper needs.
type Session interface {
	WithTransaction(ctx context.Context, fn func(ctx context.Context) (any, error), opts ...options.Lister[options.TransactionOptions]) (any, error)
	EndSession(ctx context.Context)
}

var _ Session = (*mongo.Session)(nil)

// Begin starts a session. FromClient is the production implementation.
type Begin func() (Session, error)

// FromClient starts sessions on a real client.
func FromClient(c *mongo.Client) Begin {
	return func() (Session, error) {
		s, err := c.StartSession()
		if err != nil {
			return nil, err
		}
		return s, nil
	}
}

// Do runs fn inside a transaction. The ctx given to fn carries the session:
// every collection call inside fn must use it, or the call runs outside the
// transaction. The driver may call fn more than once (transient errors) and
// retries the commit, so fn must be safe to repeat and must not do side
// effects such as sending e-mail.
func Do(ctx context.Context, begin Begin, fn func(ctx context.Context) error) error {
	s, err := begin()
	if err != nil {
		return err
	}
	defer s.EndSession(ctx)

	opts := options.Transaction().
		SetReadConcern(readconcern.Snapshot()).
		SetWriteConcern(writeconcern.Majority())

	_, err = s.WithTransaction(ctx, func(ctx context.Context) (any, error) {
		return nil, fn(ctx)
	}, opts)
	return err
}

// ErrInsufficientFunds is a business error: it aborts the transaction and is
// not retried.
var ErrInsufficientFunds = errors.New("txn: insufficient funds")

// Ledger moves money. Both calls must receive the transaction ctx.
type Ledger interface {
	Debit(ctx context.Context, account string, cents int64) error
	Credit(ctx context.Context, account string, cents int64) error
}

// Transfer debits and credits atomically: both happen or neither does.
func Transfer(ctx context.Context, begin Begin, l Ledger, from, to string, cents int64) error {
	return Do(ctx, begin, func(ctx context.Context) error {
		if err := l.Debit(ctx, from, cents); err != nil {
			return err
		}
		return l.Credit(ctx, to, cents)
	})
}

The tests use a fake session that models the documented contract (run the callback, commit on success, abort on error, re-run on the TransientTransactionError label). This tests the code around the driver, not the driver. They prove: a transfer commits both sides; a business error (ErrInsufficientFunds) aborts without a retry and leaves the balances alone; a transient error on the credit re-runs the callback once (two rounds, two debit calls) while the balances change only once; and a failure to start a session is returned unchanged.

go
package txn

import (
	"context"
	"errors"
	"testing"

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

// memLedger stages writes and publishes them only on commit, like a
// transaction would.
type memLedger struct {
	committed map[string]int64
	staged    map[string]int64
	calls     int
	failOnce  bool
}

func newLedger() *memLedger {
	return &memLedger{committed: map[string]int64{"a": 1000, "b": 0}}
}

func (l *memLedger) begin() {
	l.staged = map[string]int64{}
	for k, v := range l.committed {
		l.staged[k] = v
	}
}

func (l *memLedger) Debit(_ context.Context, acct string, c int64) error {
	l.calls++
	if l.staged[acct] < c {
		return ErrInsufficientFunds
	}
	l.staged[acct] -= c
	return nil
}

func (l *memLedger) Credit(_ context.Context, acct string, c int64) error {
	if l.failOnce {
		l.failOnce = false
		return mongo.CommandError{Code: 112, Name: "WriteConflict", Labels: []string{"TransientTransactionError"}}
	}
	l.staged[acct] += c
	return nil
}

// fakeSession models the documented WithTransaction contract: run the callback,
// commit on success, abort on error, and re-run the whole callback when the
// error carries the TransientTransactionError label.
type fakeSession struct {
	l      *memLedger
	ended  bool
	opts   int
	rounds int
}

func (f *fakeSession) WithTransaction(ctx context.Context, fn func(context.Context) (any, error), opts ...options.Lister[options.TransactionOptions]) (any, error) {
	f.opts = len(opts)
	for {
		f.rounds++
		f.l.begin()
		res, err := fn(ctx)
		if err == nil {
			f.l.committed = f.l.staged
			return res, nil
		}
		var le mongo.LabeledError
		if errors.As(err, &le) && le.HasErrorLabel("TransientTransactionError") {
			continue
		}
		return nil, err
	}
}

func (f *fakeSession) EndSession(context.Context) { f.ended = true }

func TestTransferCommits(t *testing.T) {
	l := newLedger()
	s := &fakeSession{l: l}
	err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 400)
	if err != nil {
		t.Fatal(err)
	}
	if l.committed["a"] != 600 || l.committed["b"] != 400 {
		t.Fatalf("balances %v", l.committed)
	}
	if !s.ended || s.opts != 1 {
		t.Fatalf("session ended=%v opts=%d", s.ended, s.opts)
	}
}

func TestBusinessErrorAbortsWithoutRetry(t *testing.T) {
	l := newLedger()
	s := &fakeSession{l: l}
	err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 5000)
	if !errors.Is(err, ErrInsufficientFunds) {
		t.Fatalf("got %v", err)
	}
	if s.rounds != 1 {
		t.Fatalf("a business error must not be retried, rounds=%d", s.rounds)
	}
	if l.committed["a"] != 1000 || l.committed["b"] != 0 {
		t.Fatalf("nothing may be committed: %v", l.committed)
	}
}

// The callback runs twice, yet the balances change once: the aborted first
// attempt left nothing behind. A side effect outside the transaction would
// have run twice, which is the rule the doc comment on Do states.
func TestTransientErrorReRunsCallbackOnce(t *testing.T) {
	l := newLedger()
	l.failOnce = true
	s := &fakeSession{l: l}
	if err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 400); err != nil {
		t.Fatal(err)
	}
	if s.rounds != 2 || l.calls != 2 {
		t.Fatalf("rounds=%d debit calls=%d, want 2 and 2", s.rounds, l.calls)
	}
	if l.committed["a"] != 600 || l.committed["b"] != 400 {
		t.Fatalf("balances %v", l.committed)
	}
}

func TestBeginErrorIsReturned(t *testing.T) {
	boom := errors.New("no session")
	err := Do(context.Background(), func() (Session, error) { return nil, boom }, func(context.Context) error { return nil })
	if !errors.Is(err, boom) {
		t.Fatalf("got %v", err)
	}
}
Session.WithTransaction: the callback may run more than onceStartSessionrun callback fnctx carries the sessioncommitEndSession, returnnilabort transactionon any errorTransientTransactionError?yes: retry up to 120 sno: return the error1 Every collection call inside fn must use the ctx passed to fn, or it runs outside the transaction.2 Never swallow an error inside fn: return it, or the driver cannot tell the transaction was aborted.3 No e-mail, HTTP call or counter increment in fn: a retry repeats it.
QuestionAnswer
Which deployments?replica set (feature compatibility version 4.0 or newer) and sharded cluster (4.2 or newer), per the manual
Standalone mongod?no
Nested transactions?no (the Laravel package raises a RuntimeException)
Default retry window of WithTransaction?120 seconds (withTransactionTimeout in the driver source)
Does the callback ctx matter?yes: a call that uses another ctx runs outside the transaction
Side effects in the callback?no: a retry repeats them

Real scenario: a money transfer between two account documents; creating an order and decrementing stock in two collections; moving a document between collections.

Fix / how to use it: first try to model the change as one document, which needs no transaction; when you need one, start it in the service layer, pass the ctx to every repository call, keep it short, and do e-mail or queue publishing after commit (or through an outbox, see Outbox Pattern). A single-node replica set is enough for development.

Read and write concerns Important ​

In plain words: A write concern says how many servers must confirm a write before you hear "ok". A read concern says how safe the data you read must be: possibly rolled back, or confirmed by a majority.

Common misunderstanding: "An acknowledged write is durable." Acknowledgement depends on the write concern: with w: 1 only the primary has it, and if the primary fails before replication the write can be rolled back. With majority it survives a failover. Concerns cost latency: the stronger the promise, the longer the wait.

Definition: packages go.mongodb.org/mongo-driver/v2/mongo/writeconcern (Majority(), W1(), Journaled(), Unacknowledged(), Custom(tag)) and .../readconcern (Local(), Available(), Majority(), Linearizable(), Snapshot()), set on the client (SetWriteConcern, SetReadConcern), the database or collection, or per transaction. Read preference (readpref.Primary(), Secondary(), ...) chooses which member serves reads.

ConcernPromiseCostUse
write w: 1the primary applied itlowestlogs, metrics
write majoritya majority of members have it, survives failoverone replication round tripmoney, orders, anything you cannot lose
write journaledwritten to the on-disk journaldisk syncextra durability on one node
read localthe node's latest data, may be rolled backlowestmost reads
read majoritydata a majority has acknowledgedmay be slightly behindread-after-failover safety
read snapshota consistent point-in-time viewused in transactionsmulti-document reads
read linearizablereflects every earlier majority writeslowest, primary onlyrare, strict reads

Real scenario: an order write with majority and a read of the order page with local from a secondary (stale by a few hundred milliseconds, which is fine for a catalogue and not for "my order was just placed"); a transaction with snapshot reads and a majority write. The replication background is in Replication, Read Replicas & Failover.

Fix / how to use it: set a safe default on the client (majority writes), loosen it per collection for data you can lose, and read your own writes from the primary.

Change streams and GridFS Important ​

In plain words: A change stream is a live feed of what changes in a collection, database or cluster: inserts, updates, deletes. GridFS stores files bigger than a document by cutting them into chunks.

Common misunderstanding: "A change stream is a queue." It is a tail of the oplog: you must persist the resume token yourself to continue after a restart, a gap longer than the oplog window cannot be resumed, and it needs a replica set or sharded cluster like transactions do. For GridFS: "I will put a 100 MB file in a field." A document stops at 16 MiB.

Definition: coll.Watch(ctx, pipeline, options.ChangeStream().SetFullDocument(options.UpdateLookup).SetResumeAfter(token)) returns a *mongo.ChangeStream with Next, Decode, Err, ResumeToken and Close. The pipeline can hold $match on operationType so the server filters. The snippet's Follow decodes each event into Event, returns the last resume token and closes the stream with a detached context so cleanup still runs after cancellation. The tests cover the pipeline document and decoding an event; the stream itself needs a server and is "expected, not run". GridFS pointer: the manual page "GridFS" (mongodb.com/docs/manual/core/gridfs/) describes the two collections fs.files and fs.chunks, and the driver offers bucket := db.GridFSBucket() with UploadFromStream and DownloadToStream (see the source mongo/gridfs_bucket.go). For large files in a real system most teams store the bytes in object storage and keep a URL in the document, which is the subject of File Uploads, S3 & Serving from a CDN.

go
// Package changes tails a collection with a change stream. Change streams need
// a replica set or sharded cluster, like transactions.
package changes

import (
	"context"

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

// Event is the part of a change event the application reads.
type Event struct {
	OperationType string `bson:"operationType"`
	DocumentKey   struct {
		ID bson.ObjectID `bson:"_id"`
	} `bson:"documentKey"`
	FullDocument bson.Raw `bson:"fullDocument,omitempty"`
}

// Pipeline keeps only the listed operation types, filtered on the server.
func Pipeline(ops ...string) mongo.Pipeline {
	return mongo.Pipeline{{{Key: "$match", Value: bson.D{
		{Key: "operationType", Value: bson.D{{Key: "$in", Value: ops}}},
	}}}}
}

// Follow reads events until ctx ends or the stream fails. It returns the last
// resume token so the caller can persist it and continue after a restart:
// pass it back as resume (nil starts from now).
func Follow(ctx context.Context, c *mongo.Collection, resume bson.Raw, handle func(Event) error) (bson.Raw, error) {
	opts := options.ChangeStream().SetFullDocument(options.UpdateLookup)
	if resume != nil {
		opts.SetResumeAfter(resume)
	}
	cs, err := c.Watch(ctx, Pipeline("insert", "update", "replace", "delete"), opts)
	if err != nil {
		return resume, err
	}
	defer cs.Close(context.WithoutCancel(ctx))

	token := resume
	for cs.Next(ctx) {
		var ev Event
		if err := cs.Decode(&ev); err != nil {
			return token, err
		}
		if err := handle(ev); err != nil {
			return token, err
		}
		token = cs.ResumeToken()
	}
	return token, cs.Err()
}
go
package changes

import (
	"testing"

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

func TestPipeline(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"p": Pipeline("insert", "delete")}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"p":[{"$match":{"operationType":{"$in":["insert","delete"]}}}]}`
	if string(b) != want {
		t.Fatalf("got %s", b)
	}
}

func TestDecodeEvent(t *testing.T) {
	id := bson.NewObjectID()
	raw, err := bson.Marshal(bson.D{
		{Key: "operationType", Value: "update"},
		{Key: "documentKey", Value: bson.D{{Key: "_id", Value: id}}},
		{Key: "fullDocument", Value: bson.D{{Key: "email", Value: "a@example.test"}}},
	})
	if err != nil {
		t.Fatal(err)
	}
	var ev Event
	if err := bson.Unmarshal(raw, &ev); err != nil {
		t.Fatal(err)
	}
	if ev.OperationType != "update" || ev.DocumentKey.ID != id {
		t.Fatalf("event %+v", ev)
	}
	if ev.FullDocument.Lookup("email").StringValue() != "a@example.test" {
		t.Fatal("full document missing")
	}
}
app                                   mongod
1  Watch(ctx, $match insert/update) ─▶ open stream at "now" (or after the resume token)
2                                      ... a write happens somewhere ...
3  Next → true ◀───────────────────── event { operationType, documentKey, fullDocument, _id: <token> }
4  handle(event); save ResumeToken to a durable store
5  process restarts: Watch(..., SetResumeAfter(saved token)) ─▶ continues after the last handled event

Real scenario: invalidate a cache when a product changes; push order status changes to a websocket; feed a search index; an audit trail. For cross-service events the more robust design is an outbox (see Outbox Pattern) and the broker topics in Event-Driven Go.

Fix / how to use it: persist the token after handling each event (at-least-once: handlers must be idempotent), match on the server, and handle the "resume token not found" error with a full resync.

Error handling: ErrNoDocuments, duplicate key 11000, timeouts Must-know ​

In plain words: The driver returns many kinds of errors. Your code should recognise a few and turn them into its own language: not found, conflict, timeout, unavailable.

Common misunderstanding: "Compare err.Error() with a string" or "type-assert to mongo.WriteException". Strings change between server versions, and a duplicate key can arrive as a WriteException, a BulkWriteException or a CommandError. Use the helpers: mongo.IsDuplicateKeyError(err) "returns true if err is a duplicate key error" and, for bulk errors, "if at least one of the errors is a duplicate key error"; mongo.IsTimeout(err); mongo.IsNetworkError(err); errors.Is(err, mongo.ErrNoDocuments).

Definition: the helper checks error codes 11000 (DuplicateKey), 11001, 12582 and a message-qualified 16460. The manual's error-code list shows 11000 as DuplicateKey. Server errors implement mongo.ServerError with HasErrorCode(code), HasErrorLabel(label) and ErrorCodes().

ErrorCheckDomain meaningHTTP
mongo.ErrNoDocumentserrors.Isnot found404
duplicate key, code 11000mongo.IsDuplicateKeyErrorconflict409
deadline passedmongo.IsTimeout or errors.Is(err, context.DeadlineExceeded)timeout, outcome of a write unknown504
client cancellederrors.Is(err, context.Canceled)caller leftnone (log at info)
network or server selectionmongo.IsNetworkError, server selection error textunavailable503
document validation failure, code 121HasErrorCode(121)invalid input that passed Go checks422 or 500
TransientTransactionError labelHasErrorLabelretry the whole transactionhandled by WithTransaction

Real scenario: a signup handler returns 409 for a taken email without a prior lookup; a read endpoint returns 404 for a missing id; a timeout becomes a 504 and a metric.

Fix / how to use it: map in one place (the repository's mapErr), wrap with %w so logs keep the driver detail, and let handlers compare only with your domain errors (see Errors, Panic, Recover & Defer).

Schema validation: $jsonSchema Important ​

In plain words: MongoDB lets you attach rules to a collection ("email is a string, created_at is a date") so the server rejects documents that break them, even if they come from a bug, a script or another service.

Common misunderstanding: "Validation is a replacement for my Go checks." It is the last line of defence, not the first: the error it produces is a server error with code 121, not a friendly message. Also, adding a validator does not check old documents unless you ask: with validationLevel: "moderate" existing invalid documents are left alone on updates that do not touch them.

Definition: $jsonSchema is a query operator that matches documents against a JSON Schema subset (bsonType, required, properties, pattern, minimum...). Set it as the collection validator at creation (options.CreateCollection().SetValidator(...).SetValidationLevel("strict").SetValidationAction("error")) or later with the collMod command through db.RunCommand. validationAction: "warn" logs instead of rejecting, useful while you clean old data.

go
// Package schema builds a $jsonSchema validator so the database refuses
// documents that break the shape the Go structs assume.
package schema

import (
	"context"

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

// Users returns the validator document for the users collection.
func Users() bson.D {
	return bson.D{{Key: "$jsonSchema", Value: bson.D{
		{Key: "bsonType", Value: "object"},
		{Key: "required", Value: bson.A{"email", "name", "created_at"}},
		{Key: "properties", Value: bson.D{
			{Key: "email", Value: bson.D{
				{Key: "bsonType", Value: "string"},
				{Key: "pattern", Value: `^[^@\s]+@[^@\s]+$`},
			}},
			{Key: "name", Value: bson.D{{Key: "bsonType", Value: "string"}, {Key: "minLength", Value: 1}}},
			{Key: "age", Value: bson.D{{Key: "bsonType", Value: "int"}, {Key: "minimum", Value: 0}}},
			{Key: "created_at", Value: bson.D{{Key: "bsonType", Value: "date"}}},
		}},
	}}}
}

// Create makes the collection with the validator. validationAction "error"
// rejects bad writes; "warn" only logs them (useful while migrating).
func Create(ctx context.Context, db *mongo.Database, name string) error {
	return db.CreateCollection(ctx, name, options.CreateCollection().
		SetValidator(Users()).
		SetValidationLevel("strict").
		SetValidationAction("error"))
}

// Modify changes the validator of an existing collection with collMod.
func Modify(ctx context.Context, db *mongo.Database, name string) error {
	cmd := bson.D{
		{Key: "collMod", Value: name},
		{Key: "validator", Value: Users()},
		{Key: "validationLevel", Value: "moderate"},
	}
	return db.RunCommand(ctx, cmd).Err()
}

The tests assert the validator's shape (the $jsonSchema.required array has three fields, the email pattern is present) and that the required fields match the struct's keys. A related detail the models test pins: bsonType: "int" means BSON int32 and "long" int64, and a Go int that fits is written as int32 while an int64 value is written as int64, so choose the schema type with the Go type in mind.

go
package schema

import (
	"reflect"
	"strings"
	"testing"

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

	"academy/mongodb-with-go/models"
)

func TestValidatorShape(t *testing.T) {
	raw, err := bson.Marshal(Users())
	if err != nil {
		t.Fatal(err)
	}
	r := bson.Raw(raw)
	req, err := r.LookupErr("$jsonSchema", "required")
	if err != nil {
		t.Fatal(err)
	}
	arr, ok := req.ArrayOK()
	if !ok {
		t.Fatal("required must be an array")
	}
	vals, _ := arr.Values()
	if len(vals) != 3 {
		t.Fatalf("expected 3 required fields, got %d", len(vals))
	}
	if _, err := r.LookupErr("$jsonSchema", "properties", "email", "pattern"); err != nil {
		t.Fatal("email pattern missing")
	}
}

// bsonKeys returns the document keys of a struct, from its bson tags, with
// inline structs flattened. Fields tagged "-" and omitempty fields are listed
// separately because omitempty fields cannot be "required".
func bsonKeys(t reflect.Type) (always, optional []string) {
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		tag := f.Tag.Get("bson")
		if tag == "-" || !f.IsExported() {
			continue
		}
		parts := strings.Split(tag, ",")
		name := parts[0]
		inline, omit := false, false
		for _, o := range parts[1:] {
			inline = inline || o == "inline"
			omit = omit || o == "omitempty"
		}
		if inline {
			a, o := bsonKeys(f.Type)
			always, optional = append(always, a...), append(optional, o...)
			continue
		}
		if name == "" {
			name = strings.ToLower(f.Name)
		}
		if omit {
			optional = append(optional, name)
		} else {
			always = append(always, name)
		}
	}
	return
}

// Every field the validator requires must be a key the model always writes,
// and every property it describes must be a key of the model. Renaming a tag
// in models.User fails this test.
func TestValidatorMatchesModelTags(t *testing.T) {
	always, optional := bsonKeys(reflect.TypeOf(models.User{}))
	all := map[string]bool{}
	for _, k := range append(append([]string{}, always...), optional...) {
		all[k] = true
	}
	alwaysSet := map[string]bool{}
	for _, k := range always {
		alwaysSet[k] = true
	}
	raw, _ := bson.Marshal(Users())
	r := bson.Raw(raw)
	req, _ := r.Lookup("$jsonSchema", "required").Array().Values()
	for _, e := range req {
		if !alwaysSet[e.StringValue()] {
			t.Errorf("required field %q is not an always-written key of models.User (keys: %v)", e.StringValue(), always)
		}
	}
	props, _ := r.Lookup("$jsonSchema", "properties").Document().Elements()
	for _, p := range props {
		if !all[p.Key()] {
			t.Errorf("property %q is not a key of models.User", p.Key())
		}
	}
}

Real scenario: a shared database where several services write the users collection; a migration that tightens rules in warn mode first, then switches to error.

Fix / how to use it: keep the validator in code next to the struct, apply it at start-up or in a migration job, and test it against a real server in the integration suite.

Testing: in-memory? no — real mongod or testcontainers pointer; interface + fake repository Must-know ​

In plain words: Most of the logic around the database can be tested without a database. For the rest, run a real mongod.

Common misunderstanding: "There is an in-memory MongoDB for tests." There is no in-memory mock of the server in the driver. The driver's own integration helper, mtest, lives under an internal path in v2 (internal/integration/mtest), so application code cannot import it. Your choices are an interface with a fake, or a real mongod: a local one, or one started per test run with testcontainers.

Definition: three layers. Pure unit tests: marshal filters, updates and pipelines with bson.MarshalExtJSON and compare strings; marshal and unmarshal models. Fake-backed tests: implement the repository's Collection interface with a fake that builds results using mongo.NewCursorFromDocuments and mongo.NewSingleResultFromDocument, which exist in the driver for this purpose. Integration tests: a real server for what only a server can prove (unique indexes, TTL, transactions, $lookup, change streams). The Go testcontainers library has a MongoDB module (golang.testcontainers.org/modules/mongodb/) that starts a container for a test run; use it behind a build tag or a -short check so the unit suite stays fast. This chapter did not run it (no Docker here).

What you testNeeds a server?How
Filter, update, pipeline documentsnobson.MarshalExtJSON and string compare
Struct tags and round tripsnobson.Marshal, bson.Unmarshal
Repository logic and error mappingnofake Collection
Transaction callback logicnofake session
Unique index, TTL, $jsonSchemayesreal mongod
Transactions and change streamsyes, as a replica setreal mongod --replSet or a container
Connection failure behaviournoa closed port with a short server selection timeout (the snippet's test)

Real scenario: the CI unit stage runs the fast tests in seconds; a nightly job starts a container and runs go test -tags integration.

Fix / how to use it: depend on small interfaces, build fakes with the driver's constructors, and keep integration tests few and focused. See Testing & Benchmarking and Mocking with Interfaces.

Mechanics ​

What happens inside one call Important ​

In plain words: A collection call is: marshal your Go values to BSON, pick a server, send one command over a pooled connection, wait for the reply, unmarshal.

Common misunderstanding: "Each call opens a connection." The client owns a pool per server; a call checks out a connection, uses it and returns it. When all MaxPoolSize connections are busy, the next call waits (the doc says "requests to a server will block if this maximum is reached").

Definition: the steps, with the knobs that bound each one.

1  marshal filter/update/document  → BSON bytes (errors: unsupported type, bad tag)
2  select a server                 → bounded by ServerSelectionTimeout (default 30 s) and your ctx
3  check out a pooled connection   → waits when the pool is at MaxPoolSize (default 100)
4  send the command, wait          → bounded by the ctx deadline, or the client Timeout if the ctx has none
5  read the reply or first batch   → cursor commands return a batch and a cursor id
6  unmarshal into your type        → Decode errors: type mismatch, e.g. a string into an int field
7  connection returns to the pool
StepKnobFailure looks like
2 select serverSetServerSelectionTimeout, readprefserver selection error: context deadline exceeded
3 poolSetMaxPoolSize, SetMinPoolSize, SetMaxConnIdleTimecalls slow down under load with idle CPU on the app
4 executectx deadline, SetTimeoutcontext deadline exceeded, mongo.IsTimeout(err) == true
5 cursorSetBatchSize, NoCursorTimeoutCursorNotFound after the server closes an idle cursor
6 decodestruct types and tagscannot decode string into an integer type style errors

Exact names and import paths Must-know ​

ThingExact name
Modulego.mongodb.org/mongo-driver/v2
Packages.../v2/mongo, .../v2/bson, .../v2/mongo/options, .../v2/mongo/readpref, .../v2/mongo/readconcern, .../v2/mongo/writeconcern
Connectmongo.Connect(opts ...*options.ClientOptions) (*mongo.Client, error)
Optionsoptions.Client().ApplyURI(uri).SetMaxPoolSize(n)...
Id typebson.ObjectID, bson.NewObjectID(), bson.ObjectIDFromHex(s)
Ordered documentbson.D, element bson.E{Key, Value}
Pipelinemongo.Pipeline ([]bson.D)
Sentinelmongo.ErrNoDocuments
Helpersmongo.IsDuplicateKeyError, mongo.IsTimeout, mongo.IsNetworkError
Test helpersmongo.NewCursorFromDocuments, mongo.NewSingleResultFromDocument
Transactionclient.StartSession(), session.WithTransaction(ctx, fn, opts...), session.EndSession(ctx)
Change streamcoll.Watch(ctx, pipeline, opts...)

Exact error and limit values Important ​

ValueMeaningSource
mongo: no documents in resulttext of mongo.ErrNoDocumentsdriver source single_result.go
11000 DuplicateKeyunique index violationmanual error codes
11001, 12582, 16460 (with " E11000 " in the message)other duplicate-key forms that IsDuplicateKeyError also acceptsdriver source errors.go
121 DocumentValidationFailurea collection validator rejected the documentmanual error codes
85 IndexOptionsConflict, 86 IndexKeySpecsConflictsame index name, different definitionserver error names
16 MiBmaximum size of one documentmanual, "Documents in MongoDB must be smaller than 16 mebibytes"
120 show long WithTransaction keeps retrying a transient transactiondriver source session.go
100default MaxPoolSizedriver source clientoptions.go
30 sdefault server selection timeoutdriver source clientoptions.go
about 60 show often the TTL background task runsmanual, TTL page

Solving the classic problems ​

BugSymptomFixCost
Request JSON copied into a filter{"password":{"$ne":""}} matches everyonetyped values in builders, string fields in request structsa few builder functions
bson.M for sort, hint or index keysthe driver returns ErrMapForOrderedArgument for a multi-key sort or hint; index keys must be orderedbson.Dnone
No Close on a cursorcursors pile up on the serverdefer cur.Close(ctx), or Allnone
Ignoring cur.Err()silent truncation of resultscheck after the Next loopone line
FindOne miss treated as successzero-value struct used as if loadederrors.Is(err, mongo.ErrNoDocuments)one branch
Check-then-insert racetwo accounts with one emailunique index, map code 11000an index
Read-modify-writelost updates$inc/$set operators, guard in the filterthinking in operators
Deep skip pagespages get slowerrange pagination on _idno random page access
Missing indexslow query, high CPU, COLLSCAN in explaincreate the compound index in ESR orderwrite overhead
Unbounded embedded array16 MiB errors, slow updatesmove children to their own collectiona reference and a query
Connect without Pingfirst request fails 30 s laterPing with a short timeout at start-upa few ms
Client per requestmany connections, slow requestsone client in mainwiring
Transaction on a standalone servererror at the first transactionsingle-node replica set in developmentsetup
Side effect inside the transaction callbackduplicate e-mails after a retrydo it after commit, or use an outboxa pattern
Swallowed error inside the callbacktransaction retries until the window endsreturn every errordiscipline
omitempty on a number that can be a real zerozero never storedpointer type or no omitemptytype change

Retry rules Important ​

ErrorRetry?How
TransientTransactionErroryesWithTransaction already does, up to 120 s
UnknownTransactionCommitResultyesWithTransaction retries the commit
server selection errorwith backoffthe driver already retried once (retryable reads and writes default to true; retryable writes apply only to a replica set or sharded cluster; see SetRetryWrites)
mongo.IsTimeout on a readmaybeonly if the overall budget remains
mongo.IsTimeout on a writeonly if idempotentread back or use a natural key / idempotency key
duplicate key (11000)nomap to conflict; for upsert races retry once as an update
ErrNoDocumentsnonot found

Choosing ​

SituationUseExtra techniqueReason
Look up by a unique keyFindOne with a unique indexmap ErrNoDocumentsone index seek
List a feed or API collectionFind with range pagination on _idlimit + 1 for "has next"constant cost per page
Back-office table with page numberslimit + skipcap the page numbersimplicity beats cost at small size
Counter, balance, stockUpdateOne + $inc with a guard in the filtercheck MatchedCountatomic on one document
Create or update by natural keyupsert + unique index$setOnInsert, retry once on 11000no race, one round trip
Import or sync of many rowsBulkWrite unorderedchunks of about a thousandfar fewer round trips than one call per row
Related data read together, boundedembedsnapshot fieldsone read, one atomic write
Related data shared, large or changingreference$lookup, an index on the foreign fieldno duplication
Report over a collectionaggregation, $match firstpre-aggregate if heavyserver-side work
Change spans documentsWithTransactionidempotent callback, outbox for side effectsatomicity across documents
Several services write the same collection$jsonSchema validatorwarn first, then errorthe database enforces the shape
React to changeschange streampersisted resume tokenno polling
Very large filesobject storage, or GridFS if you must stay in MongoDBURL or file id in the documentthe 16 MiB limit
Unit testsinterface + fakedriver cursor constructorsfast and server-free
Behaviour of indexes and transactionsreal mongod or testcontainerstagged integration testsonly a server can show it

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One binary, one *mongo.Client created in main after a Ping, closed in a deferred function on shutdown (see OS Processes, Signals & Graceful Shutdown). Repositories hold *mongo.Collection handles built once; handlers receive a service that depends on small interfaces. Indexes are created at start-up from a list (the indexes package). Example: a shop where users, orders and sessions are three collections, orders embeds its lines, sessions has a TTL index, and POST /orders writes one document, so no transaction is needed.

Modular monolith and multiple databases ​

Each module owns its collections and exposes functions, not collection handles: billing does not read orders directly, it asks the orders module. Several databases (PostgreSQL for money, MongoDB for catalogue and sessions) are coordinated by the application, and nothing makes a PostgreSQL commit and a MongoDB write atomic. Order the writes so a crash leaves a recoverable state (write the durable record first), or use an outbox (see Outbox Pattern). The SQL counterpart of the repository is in database/sql & pgx, and the HTTP layer that uses it in A REST API in Go.

Microservices ​

Rule one: a collection belongs to one service. Others get its data by API or events, not by connecting to its database. Change streams can feed an indexing or cache-invalidation service, but the robust way to publish a domain event is to write the event to an outbox collection in the same transaction as the state change and let a relay publish it. Example flow: orders service writes orders and outbox in one WithTransaction; a relay tails outbox with a change stream (persisted resume token) and publishes to a broker; inventory consumes idempotently by event id (unique index on processed_events.event_id, code 11000 means "already handled"). Cross-service consistency is eventual: sagas and idempotency keys, not distributed transactions (see Idempotent Consumers & the Inbox Pattern).

Distributed data: replicas, caches, sharded clusters, multi-region ​

A production MongoDB is a replica set: one primary takes writes, secondaries replicate. Reads from secondaries (readpref.Secondary) can be stale; write concern majority protects against rollback on failover; the driver finds the new primary by itself (server selection, retryable writes), so a failover looks like a few slow calls and, for non-idempotent writes whose outcome is unknown, an ambiguous timeout. A cache in front (Redis, see Redis) turns reads into hits and adds invalidation: a change stream is a good invalidation signal. A sharded cluster splits a collection by a shard key; queries that include the shard key go to one shard, others scatter to all; a transaction across shards is slower. Choose the shard key before you need it, and see Partitioning & Sharding for the general ideas and MongoDB in Depth for MongoDB's own.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesPractice
1× (one instance, one mongod)Mistakes are invisibleone client, Ping, unique indexes, typed filters, tests with fakes
10× (several app instances, a replica set)Pool size times instance count hits the server's connection limit; slow queries showtune MaxPoolSize, majority writes, compound indexes, range pagination, explain the top queries
100× (many services, sharding, multi-region)Hot shards, scatter queries, replication lag, outbox volumechoose shard keys by access pattern, read preferences by use case, TTL and archive collections, per-service databases, pre-aggregated read models

Lab ​

1. Run the tests (real) ​

bash
export PATH=/opt/homebrew/bin:$PATH
cd docs/snippets/go/mongodb-with-go/go
gofmt -l . ; go vet ./... && go test -race -count=1 ./...
# ok  academy/mongodb-with-go/after
# ok  academy/mongodb-with-go/before
# ok  academy/mongodb-with-go/changes
# ok  academy/mongodb-with-go/connect
# ok  academy/mongodb-with-go/filters
# ok  academy/mongodb-with-go/indexes
# ok  academy/mongodb-with-go/models
# ok  academy/mongodb-with-go/pipelines
# ok  academy/mongodb-with-go/relations
# ok  academy/mongodb-with-go/repo
# ok  academy/mongodb-with-go/schema
# ok  academy/mongodb-with-go/txn
# ok  academy/mongodb-with-go/typed
# ok  academy/mongodb-with-go/updates

Real output of the run on Go 1.27.4, macOS, driver v2.8.2; no MongoDB server was running.

2. See the injected filter and the random map order (real) ​

bash
go test -count=1 -v -run TestOperatorInjection ./before | grep filter
# before_test.go:27: filter sent to the server: {"email":"a@example.test","password":{"$ne":""}}
go test -count=1 -v -run TestMapOrder ./filters | grep distinct
# filters_test.go:81: distinct serialisations of one bson.M over 200 runs: 6

The second number varies from run to run (it depends on map iteration order); any value above 1 proves the point.

3. Fail fast without a server (real) ​

bash
go test -count=1 -v -run TestOpenFails ./connect | grep failed
# connect_test.go:54: failed after 300ms: mongo ping: server selection error: context deadline exceeded,
#   current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:1, Type: Unknown,
#   Last error: dial tcp 127.0.0.1:1: connect: connection refused }, ] }

4. Unique index and duplicate key against a real server (expected, not run) ​

Start a one-node replica set (needed for transactions and change streams): mongod --replSet rs0 --dbpath /tmp/rs0 and, once, mongosh --eval 'rs.initiate()'. Then:

bash
# in mongosh
use shop
db.users.createIndex({ email: 1 }, { unique: true, name: "email_unique" })
db.users.insertOne({ email: "a@example.test", name: "Ada" })
db.users.insertOne({ email: "a@example.test", name: "Ada 2" })
# expected: MongoServerError: E11000 duplicate key error collection: shop.users index: email_unique dup key: { email: "a@example.test" }

With the Go repository, the second Insert returns an error for which errors.Is(err, repo.ErrConflict) and mongo.IsDuplicateKeyError(err) are both true.

5. A transaction that retries (compiled, expected output, not run) ​

The pieces are in the snippet module: ledger.Mongo (a txn.Ledger over an accounts collection: a guarded $inc debit whose filter holds the balance check, a $inc credit, and an atomic DebitCalls counter for attempts) and the command cmd/ledgerlab, which drops and seeds lab.accounts (a = 10000, b = 0), starts 20 concurrent txn.Transfer calls of 100 each over one client, then prints balances and the attempt count. The pure parts (the debit filter and update documents) are unit-tested; the command needs a replica set, so it was built and vetted but not run here.

go
// Package ledger is a MongoDB-backed txn.Ledger: one document per account.
package ledger

import (
	"context"
	"sync/atomic"

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

	"academy/mongodb-with-go/txn"
)

// Account is the document of the accounts collection.
type Account struct {
	ID      string `bson:"_id"`
	Balance int64  `bson:"balance"`
}

// DebitFilter matches the account only while it holds enough money, so the
// check and the write are one atomic operation on one document.
func DebitFilter(account string, cents int64) bson.D {
	return bson.D{
		{Key: "_id", Value: account},
		{Key: "balance", Value: bson.D{{Key: "$gte", Value: cents}}},
	}
}

// Delta is the $inc update for a signed amount.
func Delta(cents int64) bson.D {
	return bson.D{{Key: "$inc", Value: bson.D{{Key: "balance", Value: cents}}}}
}

// Mongo implements txn.Ledger. Every call must receive the transaction ctx.
type Mongo struct {
	Accounts *mongo.Collection
	// DebitCalls counts attempts, including retries of the same transaction.
	DebitCalls atomic.Int64
}

var _ txn.Ledger = (*Mongo)(nil)

// Debit removes cents; zero matches means insufficient funds (or no account).
func (m *Mongo) Debit(ctx context.Context, account string, cents int64) error {
	m.DebitCalls.Add(1)
	res, err := m.Accounts.UpdateOne(ctx, DebitFilter(account, cents), Delta(-cents))
	if err != nil {
		return err // keep the driver error: its labels drive the retry
	}
	if res.MatchedCount == 0 {
		return txn.ErrInsufficientFunds
	}
	return nil
}

// Credit adds cents.
func (m *Mongo) Credit(ctx context.Context, account string, cents int64) error {
	_, err := m.Accounts.UpdateOne(ctx, bson.D{{Key: "_id", Value: account}}, Delta(cents))
	return err
}
bash
# terminal 1: a one-node replica set
mkdir -p /tmp/rs0 && mongod --replSet rs0 --dbpath /tmp/rs0 --port 27017
# terminal 2: initiate once, then run the lab
mongosh --eval 'rs.initiate()'
cd docs/snippets/go/mongodb-with-go/go
MONGODB_URI='mongodb://127.0.0.1:27017/?replicaSet=rs0' go run ./cmd/ledgerlab
# expected, not run:
# transfers=20 failed=0 a=8000 b=2000 debit-attempts=<20 or more>

Expected: balances end exactly a=8000 b=2000 because every attempt either commits both writes or none; debit-attempts is at least 20 and is larger when two transfers touched the same documents at once (write conflict, label TransientTransactionError, the callback re-run). The number of retries varies from run to run; if it prints exactly 20, raise the transfer count in cmd/ledgerlab/main.go.

6. Range pagination versus skip (compiled, expected output, not run) ​

cmd/seeddocs drops lab.items, inserts 1,000,000 documents in batches of 10,000 and prints the real _id at a chosen position (read with a sort on _id plus skip), so you paste an id and not a placeholder:

bash
MONGODB_URI='mongodb://127.0.0.1:27017/?replicaSet=rs0' go run ./cmd/seeddocs -n 1000000 -pos 900000
# expected, not run: inserted=1000000 id-at-position-900000=<24 hex characters>

Then compare the two queries with the id that was printed:

bash
mongosh lab --eval '
const id = ObjectId("PASTE-THE-PRINTED-ID");
printjson(db.items.find().sort({_id:1}).skip(900000).limit(20).explain("executionStats").executionStats.totalKeysExamined);
printjson(db.items.find({_id:{$gt:id}}).sort({_id:1}).limit(20).explain("executionStats").executionStats.totalKeysExamined);'
# expected, not run: about 900020 for the skip query, about 20 for the range query

For PHP/Laravel developers ​

Laravel 13 documents MongoDB on its own page: it recommends "installing and using the mongodb/laravel-mongodb package via Composer", says the package "is officially maintained by MongoDB", and needs the mongodb PHP extension. You add a connection with 'driver' => 'mongodb' and a dsn (MONGODB_URI) in config/database.php. The package then gives Eloquent models stored in MongoDB collections (extending MongoDB\Laravel\Eloquent\Model), the query builder, embedded relationships, a TTL-aware cache driver, a queue driver, a GridFS Flysystem adapter and a Scout engine. The comparison with Go is a comparison of philosophies: Laravel extends the ORM you already know and hides the BSON; Go gives you the driver and you build the thin layer yourself.

php
// Laravel with mongodb/laravel-mongodb: the same user lookup and a transaction.
$user = User::where('email', $email)->first();            // null when missing, no exception
DB::transaction(function () use ($from, $to, $cents) {   // needs a replica set, like Go
    Account::where('_id', $from)->decrement('balance', $cents);
    Account::where('_id', $to)->increment('balance', $cents);
});

The Laravel MongoDB docs say the same thing about the server: "MongoDB standalone deployments do not support transactions", nested transactions are not supported (a RuntimeException is raised), and the RefreshDatabase and DatabaseTransactions test traits are not supported, so tests reset data with DatabaseMigrations instead. In Go, the equivalent of that testing constraint is the fake-behind-an-interface approach of this chapter.

Laravel MongoDB package comparison ​

Laravel MongoDB packageGo with mongo-go-driver v2
User::where('email', $e)->first() returns nullFindOne(...).Decode(&u) returns mongo.ErrNoDocuments
Eloquent attributes, castsstruct fields and bson tags
User::create([...])InsertOne
$user->increment('logins')UpdateOne with $inc
Embedded relationships (a feature the package lists)embedded slices of structs
Eloquent relations, or a raw aggregation$lookup stage in a mongo.Pipeline
DB::transaction(fn)session.WithTransaction(ctx, fn)
Indexes created by migrations or a setup jobIndexes().CreateMany at start-up or in a job
RefreshDatabase unsupportedfakes, or a real server per test run
Request lifecycle: no cancellationctx on every call

Common misconceptions ​

BeliefReality
mongo.Connect fails when the server is downIt validates options only; use Ping
bson.M and bson.D are interchangeablebson.M has no order; sort, index keys and commands need bson.D
FindOne returns nil on a missIt returns mongo.ErrNoDocuments from Decode
An empty Find is an errorIt is an empty cursor
UpdateOne errors when nothing matchesIt succeeds with MatchedCount == 0
All leaves the cursor openIt closes it; Next loops must close it
omitempty drops zero structsOnly structs with a true IsZero, such as time.Time; plain structs stay
InsertMany is atomicIt is one batch request (split by the driver above 100,000 writes); earlier documents stay when a later one fails
Transactions work on any serverReplica set or sharded cluster only
The WithTransaction callback runs onceIt may run several times; it must be idempotent
A context timeout cancels the write on the serverThe client stops waiting; the write may still apply
MongoDB is schemaless, so no schema design is neededStructs, indexes, validators and the embed/reference choice are the schema
skip is a cheap way to pageCost grows with the offset; use a range on _id
A generic repository makes the database swappableIt centralises errors and tests; filters are still MongoDB documents

Cheat sheet ​

TopicWhat to remember
Modulego.mongodb.org/mongo-driver/v2; mongo.Connect(opts) has no ctx in v2
Clientone per process, Ping at start, Disconnect on shutdown
Optionsoptions.Client().ApplyURI(uri) first, setters after; MaxPoolSize default 100; server selection 30 s
Contextsa derived ctx with a timeout on every call; the deadline wins over the client Timeout
BSONbson.D for anything ordered, bson.M only to read unknown shapes, bson.ObjectID for ids
Tags_id,omitempty, omitempty, inline, -; no tag means lowercase name
Read oneFindOne(...).Decode(&v); errors.Is(err, mongo.ErrNoDocuments)
Read manyFind, defer cur.Close(ctx), All (bounded) or Next/Decode then cur.Err()
Paginationrange on _id for feeds; skip costs grow with the offset
Updateoperators ($set, $inc, $push, $addToSet), guard in the filter, check MatchedCount
Upsertwith a unique index; $setOnInsert for create-only fields
IndexesIndexes().CreateOne/CreateMany; keys are bson.D; ESR order; TTL runs about every 60 s
Aggregationmongo.Pipeline, $match first, $lookup needs an index on the foreign field
Relationshipsembed what is read together and bounded; reference the rest; snapshot with a plan
Transactionsreplica set or sharded; WithTransaction; idempotent callback; use the callback ctx
ErrorsIsDuplicateKeyError (11000), IsTimeout, ErrNoDocuments; map at one boundary
Validation$jsonSchema via SetValidator or collMod; code 121 on rejection
Testinginterface + fake with NewCursorFromDocuments; real server for indexes, TTL, transactions

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — mongo.Connect returned no error. Is the database reachable? Must-know ​

Answer

Answer: Not necessarily. mongo.Connect returns an error only when the options are invalid; it does not contact a server. Call client.Ping(ctx, readpref.Primary()) with a short timeout at start-up. An unreachable server then shows as a server selection error after the server selection timeout (30 seconds by default, SetServerSelectionTimeout). See Connecting.

2 — Why must a sort document be a bson.D and not a bson.M? Must-know ​

Answer

Answer: The order of keys in a sort (and in index keys and commands) is part of its meaning, and a Go map iterates in random order. The driver therefore returns ErrMapForOrderedArgument for a sort or hint given as a bson.M with more than one key, and the chapter's test serialises one six-key bson.M 200 times and got several different orderings; a bson.D always keeps the order written. See BSON types.

3 — A user posts {"password": {"$ne": ""}} to your login endpoint. How does this become a bug, and how do you prevent it? Must-know ​

Answer

Answer: If the handler copies request fields into a bson.M filter, the object becomes an operator document and matches every account that has a password. Prevent it with request structs whose fields are string (an object does not decode into a string), filter builders that take typed values, and by checking the password against a stored hash in Go instead of putting it in the query. See Go: Before and After.

4 — What does omitempty do for bson.ObjectID, time.Time, a nil pointer and a plain struct value? Important ​

Answer

Answer: It omits a zero ObjectID and a zero time.Time (both have an IsZero method), and a nil pointer. A plain struct value without IsZero is never considered empty and is written as a sub-document, which is why an optional sub-document should be a pointer. omitzero is not a tag of this package in v2.8.2. See Mapping structs.

5 — FindOne found nothing. What do you get, and what does Find give for the same filter? Must-know ​

Answer

Answer: FindOne(...).Decode(&v) returns mongo.ErrNoDocuments (compare with errors.Is); Find returns an empty cursor and no error. A repository should translate the first into its own not-found error. See FindOne and Find and cursors.

6 — When must you call cursor.Close, and what does All do about it? Good to know ​

Answer

Answer: Whenever you read with Next, always close the cursor, or the server keeps its resources; defer cur.Close(ctx) right after the error check is the habit. All closes the cursor itself after reading everything, but an early return before All still needs the deferred close. After a Next loop also read cur.Err(). See Find and cursors.

7 — Why is range pagination on _id faster than limit/skip at page 10,000, and what do you give up? Must-know ​

Answer

Answer: skip makes the server walk past all skipped entries, so the cost grows with the offset. A range filter _id > last seeks straight to the position in the index, so every page costs the same. You give up jumping to an arbitrary page number, and the sort key must be unique and indexed. See Pagination.

8 — Why use $inc instead of reading a counter, adding one and saving it? Important ​

Answer

Answer: Read-modify-write has a race: two requests read the same value and the second write erases the first (a lost update). $inc is applied on the server atomically for that document. For "only if enough balance" put the condition in the filter and check MatchedCount. See Update.

9 — When do you embed and when do you reference? Important ​

Answer

Answer: Embed data that is read together with its parent, is bounded in size and has no life of its own (order lines in an order). Reference data that is shared, changes often, is queried on its own or grows without bound, and join it with $lookup or a second query. Copy a few fields as a snapshot only when you accept that the copy goes stale. A document may not exceed 16 MiB. See Relationships.

10 — What must be true of a WithTransaction callback, and which deployments allow it? Must-know ​

Answer

Answer: It runs on a replica set or a sharded cluster (not a standalone server). The callback may run more than once, so it must be idempotent and free of side effects such as e-mail; every operation inside must use the ctx the callback receives; and errors must be returned, not swallowed. The driver retries transient transactions for up to 120 seconds. See Transactions.

11 — A unique index rejects a second insert. Which code and which helper do you use, and what does the caller see? Important ​

Answer

Answer: The server error code is 11000 (DuplicateKey); mongo.IsDuplicateKeyError(err) detects it, including inside bulk errors. The repository maps it to its own ErrConflict (wrapped with %w so the driver error stays in the chain) and an HTTP handler turns that into 409. See Error handling.

12 — How do you test code that uses the driver when no MongoDB server is available? Good to know ​

Answer

Answer: Put the six methods you use behind a small interface, and write a fake that returns results built with mongo.NewCursorFromDocuments and mongo.NewSingleResultFromDocument; decoding then runs through the real BSON codecs. Test filters and pipelines by marshalling them with bson.MarshalExtJSON. The driver's own mtest helper is internal in v2, so it cannot be imported. Use a real mongod or testcontainers for indexes, TTL, transactions and change streams. See Testing.

13 — What is a change stream's resume token for? Good to know ​

Answer

Answer: Each event carries a token. If you save the token of the last handled event and pass it to SetResumeAfter when you open the stream again, the stream continues after that event, so a restart does not lose changes (as long as the oplog still covers the gap). Handling is at-least-once, so handlers must be idempotent. See Change streams and GridFS.

Glossary ​

TermMeaning
mongo-go-driver v2The official MongoDB driver for Go, module go.mongodb.org/mongo-driver/v2
mongo.ClientThe handle that owns the connection pools and monitors; one per process
mongo.ConnectCreates the client from options; does not prove the server is reachable
options.ClientBuilder for client options (ApplyURI, SetMaxPoolSize, SetTimeout...)
ApplyURIParses a connection string into client options; later setters override it
PingA cheap command that checks that a server can be selected
DisconnectCloses the pools and stops the monitors, waiting for in-use connections
context timeoutA deadline on the ctx that bounds one operation on the client side
BSONThe binary document format MongoDB stores and sends
bson.DOrdered document: a slice of bson.E
bson.MUnordered document: a Go map
bson.ABSON array: a slice of values
struct tagMetadata such as bson:"name,omitempty" that controls mapping
_idThe mandatory primary key of every document, indexed and unique
bson.ObjectIDA 12-byte id with an embedded creation timestamp
omitemptyTag option that omits empty values, including structs that have IsZero
inlineTag option that flattens an embedded struct or map into the parent
ErrNoDocumentsSentinel returned by single-document reads that find nothing
cursorA server-side result handle read in batches with Next
filterA document describing which documents to match
projectionWhich fields a read returns
range paginationPaging by "after the last _id" instead of skip
$set, $inc, $push, $addToSetUpdate operators: assign, add, append, append if absent
upsertUpdate that inserts when nothing matches
$setOnInsertUpdate operator applied only when an upsert inserts
bulk writeSeveral different write models sent together in batches of at most 100,000 writes
indexA sorted side structure for fast lookups
unique indexAn index that rejects duplicate keys with code 11000
compound indexAn index on several fields, where field order matters
TTL indexAn index on a date field that deletes documents after a delay
text indexAn index for word search over string fields
aggregation pipelineAn ordered list of stages that transform documents
$lookupPipeline stage that joins another collection
$unwindPipeline stage that outputs one document per array element
embeddingStoring related data inside the parent document
referencingStoring the id of a related document
denormalizationDuplicating data to make reads cheaper
Repository[T]A generic type that wraps a collection for documents of type T
typed filterA filter builder whose values are checked by the Go compiler
sessionServer-side context in which a transaction runs
WithTransactionRuns a callback in a transaction with automatic retry of transient errors
replica setA group of servers holding the same data with one primary
read concern / write concernHow safe a read must be / how many members must confirm a write
change streamA live feed of changes, resumable with a token
GridFSA convention for storing large files as chunks in two collections
$jsonSchemaValidation rules attached to a collection
duplicate keyError 11000 caused by a unique index violation
MaxPoolSizeMaximum connections per server in a client's pool (default 100)
fakeA test implementation of an interface used instead of a real server
testcontainersA library that starts a real MongoDB container for a test run

References ​

Built by Morteza Negahi