Skip to content

MongoDB with the Go driver

Uses mongo-go-driver v2.9. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

mongodb://app:secret@mongo.example.com:27017/shop?authSource=admin
mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin

The address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'
go mod tidy
go run .

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

main.go
// Orders example for MongoDB, unchanged on MachNoSQL.
package main
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
ctx := context.Background()
client, err := mongo.Connect(options.Client().ApplyURI(os.Getenv("MONGODB_URI")))
if err != nil {
log.Fatal(err)
}
defer func() { _ = client.Disconnect(ctx) }()
orders := client.Database("shop").Collection("orders")
if _, err := orders.DeleteMany(ctx, bson.D{}); err != nil {
log.Fatal(err)
}
_, err = orders.InsertMany(ctx, []any{
bson.D{{Key: "customer", Value: "ada"}, {Key: "item", Value: "keyboard"}, {Key: "qty", Value: 1}, {Key: "price", Value: 49.0}},
bson.D{{Key: "customer", Value: "ada"}, {Key: "item", Value: "mouse"}, {Key: "qty", Value: 2}, {Key: "price", Value: 19.5}},
bson.D{{Key: "customer", Value: "linus"}, {Key: "item", Value: "monitor"}, {Key: "qty", Value: 1}, {Key: "price", Value: 199.0}},
})
if err != nil {
log.Fatal(err)
}
var mouse bson.M
if err := orders.FindOne(ctx, bson.D{{Key: "item", Value: "mouse"}}).Decode(&mouse); err != nil {
log.Fatal(err)
}
fmt.Println(mouse)
update := bson.D{{Key: "$inc", Value: bson.D{{Key: "qty", Value: 1}}}}
if _, err := orders.UpdateOne(ctx, bson.D{{Key: "item", Value: "mouse"}}, update); err != nil {
log.Fatal(err)
}
pipeline := mongo.Pipeline{
{{Key: "$group", Value: bson.D{
{Key: "_id", Value: "$customer"},
{Key: "revenue", Value: bson.D{{Key: "$sum", Value: bson.D{{Key: "$multiply", Value: bson.A{"$qty", "$price"}}}}}},
}}},
{{Key: "$sort", Value: bson.D{{Key: "revenue", Value: -1}}}},
}
cursor, err := orders.Aggregate(ctx, pipeline)
if err != nil {
log.Fatal(err)
}
var rows []bson.M
if err := cursor.All(ctx, &rows); err != nil {
log.Fatal(err)
}
fmt.Println(rows)
}
go.mod
module example.com/machnosql/mongodb
go 1.25
require go.mongodb.org/mongo-driver/v2 v2.9.2