Databases 12 min read

Master MongoDB with Go: From Setup to CRUD Operations

This guide walks you through installing the Go MongoDB driver, establishing connections, and performing full CRUD operations—including inserting single and multiple documents, querying, updating, and deleting records—while also showing how to retrieve server status and explaining BSON handling in Go.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master MongoDB with Go: From Setup to CRUD Operations

Installing the MongoDB Go Driver

<code>mkdr mongodb
cd mongodb
go mod init
go get go.mongodb.org/mongo-driver/mongo</code>

Connecting to MongoDB

Import the required packages:

<code>package main

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

The connection URI format is:

<code>mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]</code>

Examples:

Standalone:

mongodb://localhost:27017

Replica set:

mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl

Sharded cluster:

mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017

Connect using

mongo.Connect()

with a context and client options:

<code>func main() {
    clientOptions := options.Client().ApplyURI("mongodb://admin:password@localhost:27017")
    var ctx = context.TODO()
    // Connect to MongoDB
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }
    // Verify connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
    defer client.Disconnect(ctx)
}</code>

Listing All Databases

<code>databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
    log.Fatal(err)
}
fmt.Println(databases)</code>

Working with BSON in Go

MongoDB stores JSON documents as BSON (binary JSON). The Go driver provides two series for BSON handling: the

D

series and the

Raw

series. The

D

series includes four types:

D

: ordered BSON document, used when field order matters (e.g., commands).

M

: unordered map, equivalent to

D

but without order.

A

: BSON array.

E

: a single element within a

D

document.

Inserting Data into MongoDB

Insert a Single Document

<code>// Define the document structure
type sunshareboy struct {
    Name string
    Age  int
    City string
}

// Connect to the collection (creates it if missing)
collection := client.Database("test").Collection("sunshare")
wanger := sunshareboy{"wanger", 24, "北京"}
insertOne, err := collection.InsertOne(ctx, wanger)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted a Single Document: ", insertOne.InsertedID)</code>

Insert Multiple Documents

<code>collection := client.Database("test").Collection("sunshare")
// Define several documents
dongdong := sunshareboy{"张冬冬", 29, "成都"}
huazai := sunshareboy{"华仔", 28, "深圳"}
suxin := sunshareboy{"素心", 24, "甘肃"}
god := sunshareboy{"刘大仙", 24, "杭州"}
qiaoke := sunshareboy{"乔克", 29, "重庆"}
jiang := sunshareboy{"姜总", 24, "上海"}
// Slice of documents for bulk insert
boys := []interface{}{dongdong, huazai, suxin, god, qiaoke, jiang}
insertMany, err := collection.InsertMany(ctx, boys)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertMany.InsertedIDs)</code>

Querying Data from MongoDB

Find a Single Document

<code>var result sunshareboy
filter := bson.D{{"name", "wanger"}}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)</code>

Find Multiple Documents

<code>// Limit the number of returned documents
findOptions := options.Find()
findOptions.SetLimit(5)
var results []*sunshareboy
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
    log.Fatal(err)
}
for cur.Next(context.TODO()) {
    var result sunshareboy
    err := cur.Decode(&result)
    if err != nil {
        log.Fatal(err)
    }
    results = append(results, &result)
}
fmt.Printf("Found multiple documents: %+v\n", results)
cur.Close(context.TODO())</code>

Updating MongoDB Documents

Update a Single Document

<code>filter := bson.D{{"name", "张冬冬"}}
opts := options.Update().SetUpsert(true)
update := bson.D{{"$set", bson.D{{"city", "北京"}}}}
result, err := collection.UpdateOne(context.TODO(), filter, update, opts)
if err != nil {
    log.Fatal(err)
}
if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
    fmt.Printf("Inserted a new document with ID %v\n", result.UpsertedID)
}</code>

Update Multiple Documents

<code>filter := bson.D{{"city", "北京"}}
opts := options.Update().SetUpsert(true)
update := bson.D{{"$set", bson.D{{"city", "铁岭"}}}}
result, err := collection.UpdateMany(context.TODO(), filter, update, opts)
if err != nil {
    log.Fatal(err)
}
if result.MatchedCount != 0 {
    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
    fmt.Printf("Inserted a new document with ID %v\n", result.UpsertedID)
}</code>

Deleting MongoDB Documents

<code>filter := bson.D{{"city", "铁岭"}}
deleteResult, err := collection.DeleteMany(context.TODO(), filter)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the collection\n", deleteResult.DeletedCount)</code>

Retrieving MongoDB Server Status

<code>ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
serverStatus, err := client.Database("admin").RunCommand(
    ctx,
    bsonx.Doc{{"serverStatus", bsonx.Int32(1)}},
).DecodeBytes()
if err != nil {
    fmt.Println(err)
}
fmt.Println(serverStatus)
version, err := serverStatus.LookupErr("version")
if err == nil {
    fmt.Println(version.StringValue())
}</code>

Reference Links

https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial https://godoc.org/go.mongodb.org/mongo-driver/mongo

DatabaseGoCRUDMongoDBBSONDriver
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.