You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Go library for parsing and executing MongoDB shell syntax using the native MongoDB driver.
Overview
gomongo parses MongoDB shell commands (e.g., db.users.find()) and executes them using the Go MongoDB driver, eliminating the need for external mongosh CLI.
Installation
go get github.com/bytebase/gomongo
Usage
package main
import (
"context""fmt""log""github.com/bytebase/gomongo""go.mongodb.org/mongo-driver/v2/bson""go.mongodb.org/mongo-driver/v2/mongo""go.mongodb.org/mongo-driver/v2/mongo/options"
)
funcmain() {
ctx:=context.Background()
// Connect to MongoDBclient, err:=mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))
iferr!=nil {
log.Fatal(err)
}
deferclient.Disconnect(ctx)
// Create gomongo clientgc:=gomongo.NewClient(client)
// Execute MongoDB shell commandsresult, err:=gc.Execute(ctx, "mydb", `db.users.find({ age: { $gt: 25 } })`)
iferr!=nil {
log.Fatal(err)
}
// Result.Value contains []any - type depends on operation// For find(), each element is bson.Dfor_, val:=rangeresult.Value {
doc, ok:=val.(bson.D)
if!ok {
log.Printf("unexpected type %T\n", val)
continue
}
fmt.Printf("%+v\n", doc)
}
// For countDocuments(), single element is int64countResult, err:=gc.Execute(ctx, "mydb", `db.users.countDocuments({})`)
iferr!=nil {
log.Fatal(err)
}
count, ok:=countResult.Value[0].(int64)
if!ok {
log.Fatalf("unexpected type %T\n", countResult.Value[0])
}
fmt.Printf("Count: %d\n", count)
}
Execute Options
The Execute method accepts optional configuration:
WithMaxRows
Limit the maximum number of rows returned by find() and countDocuments() operations. This is useful to prevent excessive memory usage or network traffic from unbounded queries.
// Cap results at 1000 rowsresult, err:=gc.Execute(ctx, "mydb", `db.users.find()`, gomongo.WithMaxRows(1000))
Behavior:
If the query includes .limit(N), the effective limit is min(N, maxRows)
Query limit 50 + MaxRows 1000 → returns up to 50 rows
Query limit 5000 + MaxRows 1000 → returns up to 1000 rows
aggregate() operations are not affected (use $limit stage instead)
Output Format
Results are returned as native Go types in Result.Value (a []any slice). Use Result.Operation to determine the expected type: