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.
Installing the MongoDB Go Driver
mkdr mongodb
cd mongodb
go mod init
go get go.mongodb.org/mongo-driver/mongoConnecting to MongoDB
Import the required packages:
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"
)The connection URI format is:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]Examples:
Standalone: mongodb://localhost:27017 Replica set:
mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myReplSharded cluster:
mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017Connect using mongo.Connect() with a context and client options:
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)
}Listing All Databases
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println(databases)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
// 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)Insert Multiple Documents
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)Querying Data from MongoDB
Find a Single Document
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
", result)Find Multiple Documents
// 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
", results)
cur.Close(context.TODO())Updating MongoDB Documents
Update a Single Document
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.
", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
fmt.Printf("Inserted a new document with ID %v
", result.UpsertedID)
}Update Multiple Documents
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.
", result.MatchedCount, result.ModifiedCount)
}
if result.UpsertedCount != 0 {
fmt.Printf("Inserted a new document with ID %v
", result.UpsertedID)
}Deleting MongoDB Documents
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
", deleteResult.DeletedCount)Retrieving MongoDB Server Status
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())
}Reference Links
https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial https://godoc.org/go.mongodb.org/mongo-driver/mongo
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
