### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/update/embedded-arrays Inserts sample `Drink` documents into the `drinks` collection. This setup is required to run the subsequent update examples. ```go coll := client.Database("db").Collection("drinks") docsToInsert := []any{ Drink{Description: "Matcha Latte", Sizes: []int32{12, 16, 20}, Styles: []string{"iced", "hot", "extra hot"}}, } result, err := coll.InsertMany(context.TODO(), docsToInsert) ``` -------------------------------- ### CommandStartedEvent Example Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring Sample output for a CommandStartedEvent, showing details about a command that has started. ```none *event.CommandStartedEvent { "Command": "...", "DatabaseName": "...", "CommandName": "...", "RequestID": ..., "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": "..." } ``` -------------------------------- ### Example: Explain Command Source: https://www.mongodb.com/docs/drivers/go/current/run-command An example demonstrating how to use `RunCommand` to execute the `explain` command for a `count` operation. ```APIDOC ## Example: Explain Command ### Description This example shows how to run the `explain` command to get details about a `count` operation's execution plan. ### Method `RunCommand(ctx context.Context, command interface{}, opts ...*options.RunCmdOptions) *SingleResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (interface{}) - Required - The command document, including the command name and its parameters. ### Request Example ```go db := client.Database("db") // Creates commands to count documents in a collection and explain // how the count command runs countCommand := bson.D{{"count", "flowers"}} explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}} // Retrieves results of the explain command var result bson.M err = db.RunCommand(context.TODO(), explainCommand).Decode(&result) ``` ### Response #### Success Response (200) - **SingleResult** - Contains the explain command response, typically including `queryPlanner`. #### Response Example ```json { "queryPlanner": { "namespace": "db.flowers", "indexFilterSet": false, "parsedQuery": { ... }, "queryHash": "...", "planSummary": "...", "rejectedPlans": [] }, "ok": 1, "operationTime": "...", "$clusterTime": { "clusterTime": "...", "signature": { "hash": "...", "keyId": "..." } } } ``` ``` -------------------------------- ### Install Snappy Compression Dependency Source: https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/network-compression Add the Snappy compression algorithm dependency to your Go application using the `go get` command. ```bash go get github.com/golang/snappy ``` -------------------------------- ### Basic HTTP Server Structure in Go Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Set up a basic HTTP server in Go. This includes defining an App struct, a Start method to run the server, and a main function to initialize and start the application. ```go package main import ( "context" "log" "net/http" "os" "github.com/joho/godotenv" ) type App struct { } func (app App) Start() error { const serverAddr string = "0.0.0.0:3001" log.Printf("Starting HTTP server: %s\n", serverAddr) return http.ListenAndServe(serverAddr, nil) } func main() { app := App{} log.Println(app.Start()) } ``` -------------------------------- ### Load Sample Data into 'tea' Collection Source: https://www.mongodb.com/docs/drivers/go/current/aggregation Inserts multiple sample 'Tea' documents into the 'tea' collection in the 'db' database. This setup is required to run the subsequent aggregation examples. ```go coll := client.Database("db").Collection("tea") docs := []any{ Tea{Type: "Masala", Category: "black", Toppings: []string{"ginger", "pumpkin spice", "cinnamon"}, Price: 6.75}, Tea{Type: "Gyokuro", Category: "green", Toppings: []string{"berries", "milk foam"}, Price: 5.65}, Tea{Type: "English Breakfast", Category: "black", Toppings: []string{"whipped cream", "honey"}, Price: 5.75}, Tea{Type: "Sencha", Category: "green", Toppings: []string{"lemon", "whipped cream"}, Price: 5.15}, Tea{Type: "Assam", Category: "black", Toppings: []string{"milk foam", "honey", "berries"}, Price: 5.65}, Tea{Type: "Matcha", Category: "green", Toppings: []string{"whipped cream", "honey"}, Price: 6.45}, Tea{Type: "Earl Grey", Category: "black", Toppings: []string{"milk foam", "pumpkin spice"}, Price: 6.15}, Tea{Type: "Hojicha", Category: "green", Toppings: []string{"lemon", "ginger", "milk foam"}, Price: 5.55}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Install Zstandard Compression Dependency Source: https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/network-compression Add the Zstandard compression algorithm dependency to your Go application using the `go get` command. ```bash go get -u github.com/klauspost/compress ``` -------------------------------- ### Install Third-Party Logging Packages Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/logging Run these go get commands to download the `logrus` and `logrusr` packages required for integrating `logrus` with the MongoDB Go Driver. ```bash go get github.com/bombsimon/logrusr/v4 go get github.com/sirupsen/logrus ``` -------------------------------- ### Install AWS SDK for Bedrock Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Installs the AWS SDK for Go v2, including packages for general configuration and the Bedrock runtime client. ```sh go get github.com/aws/aws-sdk-go-v2/config go get github.com/aws/aws-sdk-go-v2/service/bedrockruntime ``` -------------------------------- ### List Collections to Verify Time Series Creation in Go Source: https://www.mongodb.com/docs/drivers/go/current/time-series Run the `listCollections` command using `RunCommand` to verify the creation of a time series collection. This example includes full setup for connecting to MongoDB and running the command. ```go package main import ( "context" "encoding/json" "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() { var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) db := client.Database("myDB") // Creates a command to list collections command := bson.D{{"listCollections", 1}} var result bson.M // Runs the command on the database commandErr := db.RunCommand(context.TODO(), command).Decode(&result) if commandErr != nil { panic(commandErr) } // Prints the command results output, outputErr := json.MarshalIndent(result, "", " ") if outputErr != nil { panic(outputErr) } fmt.Printf("%s\n", output) } ``` -------------------------------- ### Example Log Output (Default Logger) Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/logging Example console output showing debug-level logs for connection and command events when using the default logger configuration. ```console level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection checkout started level: 1 DEBUG, message: Connection created level: 1 DEBUG, message: Connection ready level: 1 DEBUG, message: Connection checked out level: 1 DEBUG, message: Command started level: 1 DEBUG, message: Command succeeded level: 1 DEBUG, message: Connection checked in ``` -------------------------------- ### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/update/upsert Loads sample plant data into the 'plants' collection. This is a prerequisite for running the upsert example. ```go coll := client.Database("db").Collection("plants") docs := []any{ Plant{Species: "Polyscias fruticosa", PlantID: 1, Height: 27.6}, Plant{Species: "Polyscias fruticosa", PlantID: 2, Height: 34.9}, Plant{Species: "Ledebouria socialis", PlantID: 1, Height: 11.4}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### InsertOne() Output Example Source: https://www.mongodb.com/docs/drivers/go/current/crud/insert Example output showing the _id of a document inserted with InsertOne(). ```none Inserted document with _id: ObjectID("...") ``` -------------------------------- ### Install MongoDB Go Driver and godotenv Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Install the necessary Go modules for MongoDB Atlas integration and environment variable loading. ```sh go get github.com/joho/godotenv go get go.mongodb.org/mongo-driver/v2 ``` -------------------------------- ### Install Image Editing Module Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Installs the necessary Go module for image manipulation, specifically the draw package. ```sh go get golang.org/x/image/draw ``` -------------------------------- ### Install MongoDB Go Driver and AWS Lambda SDK Source: https://www.mongodb.com/docs/drivers/go/current/connect/go-lambda Install the necessary Go packages for MongoDB interaction and AWS Lambda integration. Ensure these are added to your project's dependencies. ```bash go get go.mongodb.org/mongo-driver/v2/mongo go get github.com/aws/aws-lambda-go/lambda ``` -------------------------------- ### Subscribe to Connection Pool Events Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring Instantiate a PoolMonitor and connect to a deployment to subscribe to connection pool events. This example shows how to capture `PoolEvent`s. ```go var eventArray []*event.PoolEvent cxnMonitor := &event.PoolMonitor{ Started: func(e *event.PoolEvent) { eventArray = append(eventArray, e) }, } clientOpts := options.Client().ApplyURI(uri).SetPoolMonitor(cxnMonitor) client, err := mongo.Connect(clientOpts) ``` -------------------------------- ### Add Gin and MongoDB Driver Dependencies Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application Install the necessary dependencies for the Gin web framework and the MongoDB Go Driver. ```bash go get github.com/gin-gonic/gin go get go.mongodb.org/mongo-driver/v2/mongo ``` -------------------------------- ### Run a Database Command (dbStats) Source: https://www.mongodb.com/docs/drivers/go/current/run-command This Go code example demonstrates how to connect to a MongoDB instance and retrieve statistics for a specific database using the `RunCommand` method. ```APIDOC ## Run a Database Command (dbStats) ### Description This example connects to a MongoDB instance using a connection URI and retrieves statistics about the `sample_restaurants` database. It utilizes the `RunCommand` method to execute the `dbStats` command. ### Method `db.RunCommand(context.Context, command interface{}) *mongo.SingleResult` ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `command`: A `bson.D` or `bson.M` representing the database command to run. For `dbStats`, it would be `bson.D{{"dbStats", 1}}`. ### Request Example ```go db := client.Database("sample_restaurants") // Retrieves statistics about the specified database command := bson.D{{"dbStats", 1}} var result bson.M // Runs the command and prints the database statistics err := db.RunCommand(context.TODO(), command).Decode(&result) ``` ### Response #### Success Response (200) Returns a `bson.M` containing the database statistics. The exact fields may vary but typically include: - **db** (string) - The name of the database. - **collections** (int32) - The number of collections in the database. - **objects** (int32) - The number of documents in the database. - **avgObjSize** (float64) - The average size of a document in the database. - **dataSize** (float64) - The total size of the data in the database. - **numExtents** (int32) - **indexes** (int32) - The number of indexes in the database. - **indexSize** (float64) - The total size of the indexes in the database. - **fileSize** (float64) - **ok** (float64) - Indicates if the command executed successfully (usually 1). #### Response Example ```json { "avgObjSize": 548.4101901854896, "collections": 2, "dataSize": 14014074, "db": "sample_restaurants", "fileSize": 0, "indexSize": 286720, "indexes": 2, "nsSizeMB": 0, "numExtents": 0, "objects": 25554, "ok": 1, "storageSize": 8257536, "totalFreeStorageSize": 0, "views": 0 } ``` ``` -------------------------------- ### Limit and Sort/Skip Options Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/specify-return-documents The driver applies the limit behavior last, regardless of option order. This example demonstrates limiting, sorting, and skipping documents in a `Find` operation. ```go opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetSkip(1).SetLimit(2) ``` ```go opts := options.Find().SetLimit(2).SetSort(bson.D{{"enrollment", -1}}).SetSkip(1) ``` ```go filter := bson.D{} opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetLimit(2).SetSkip(1) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) } ``` -------------------------------- ### CommandSucceededEvent Example Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring Sample output for a CommandSucceededEvent, detailing a successfully executed command. ```none *event.CommandSucceededEvent { "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": null, "Reply": "..." } ``` -------------------------------- ### Set Up Basic Gin Application Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application Create a main.go file to set up a basic Gin application with a root endpoint. ```go package main import ( "log" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello World", }) }) if err := r.Run(); err != nil { log.Fatal("Failed to start server:", err) } } ``` -------------------------------- ### Create and Initialize Go Project Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application Create a new directory for your project and initialize a Go module to manage dependencies. ```bash mkdir mflix cd mflix go mod init mflix ``` -------------------------------- ### ServerDescriptionChangedEvent Example Document Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is a sample JSON document representing a ServerDescriptionChangedEvent. It details the previous and new descriptions of a server's state, including its address, topology information, and configuration. ```json *event.ServerDescriptionChangedEvent { "Address": "...", "TopologyID": "...", "PreviousDescription": { "Addr": "...", "Arbiters": null, "AverageRTT": 0, "AverageRTTSet": false, "Compression": null, "CanonicalAddr": "...", "ElectionID": "...", "HeartbeatInterval": 0, "HelloOK": false, "Hosts": null, "LastError": null, "LastUpdateTime": "...", "LastWriteTime": "...", "MaxBatchCount": 0, "MaxDocumentSize": 0, "MaxMessageSize": 0, "Members": null, "Passives": null, "Passive": false, "Primary": "...", "ReadOnly": false, "ServiceID": null, "SessionTimeoutMinutes": 0, "SetName": "...", "SetVersion": 0, "Tags": null, "TopologyVersion": null, "Kind": 0, "WireVersion": null }, "NewDescription": { "Addr": "...", "Arbiters": null, "AverageRTT": ..., "AverageRTTSet": true, "Compression": null, "CanonicalAddr": "...", "ElectionID": "...", "HeartbeatInterval": ..., "HelloOK": true, "Hosts": [...], "LastError": null, "LastUpdateTime": "...", "LastWriteTime": "...", "MaxBatchCount": ..., "MaxDocumentSize": ..., "MaxMessageSize": ..., "Members": [...], "Passives": null, "Passive": false, "Primary": "...", "ReadOnly": false, "ServiceID": null, "SessionTimeoutMinutes": 30, "SetName": "...", "SetVersion": 9, "Tags": [...], "TopologyVersion": {...}, "Kind": 10, "WireVersion": {...} } } ``` -------------------------------- ### Go Main Function with Gin and MongoDB Setup Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application Initializes MongoDB connection, sets up Gin router, and registers route handlers for movie endpoints. Includes connection verification and graceful disconnection. ```go func main() { // Connects to MongoDB serverAPI := options.ServerAPI(options.ServerAPIVersion1) opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI) client, err := mongo.Connect(opts) if err != nil { log.Fatal("Could not connect to MongoDB:", err) } // Ensures the client disconnects when main exits defer func() { if err := client.Disconnect(context.TODO()); err != nil { log.Fatal("Error disconnecting from MongoDB:", err) } }() // Pings the database to verify connection if err := client.Ping(context.TODO(), nil); err != nil { log.Fatal("Could not ping MongoDB:", err) } r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello World", }) }) // Registers movie endpoints r.GET("/movies", func(c *gin.Context) { getMovies(c, client) }) r.GET("/movies/:id", func(c *gin.Context) { getMovieByID(c, client) }) r.POST("/movies/aggregations", func(c *gin.Context) { aggregateMovies(c, client) }) if err := r.Run(); err != nil { log.Fatal("Failed to start server:", err) } } ``` -------------------------------- ### Connection Establishment with Timeout Source: https://www.mongodb.com/docs/drivers/go/current/context Demonstrates setting a client connection timeout and a context deadline for an InsertOne operation. The connection establishment will respect the shorter of the two timeouts. ```go opts := options.Client() opts.SetConnectTimeout(1*time.Second) client, err := mongo.Connect(opts) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) deffer cancel() client.Database("").Collection("").InsertOne(ctx, bson.D{{"x",1}}) ``` -------------------------------- ### Add MongoDB Go Driver Dependency Source: https://www.mongodb.com/docs/drivers/go/current/get-started Add the MongoDB Go Driver as a project dependency using `go get`. This command downloads and installs the driver. ```shell go get go.mongodb.org/mongo-driver/v2/mongo ``` -------------------------------- ### Initialize Go Project Source: https://www.mongodb.com/docs/drivers/go/current/get-started Create and initialize a new Go project directory using `go mod`. This sets up the project for dependency management. ```shell mkdir go-quickstart cd go-quickstart go mod init go-quickstart ``` -------------------------------- ### Create main.go File Source: https://www.mongodb.com/docs/drivers/go/current/get-started Create the `main.go` file in your project's base directory. This file will contain your Go application code. ```shell touch main.go ``` -------------------------------- ### Count Documents with Filter in Go Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/count This example demonstrates connecting to MongoDB, defining a filter for 'American' cuisine, and then counting documents that match this filter using CountDocuments(). It also shows how to get an estimated document count for the entire collection. ```go // Counts documents in a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{}, } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Specifies a filter to match documents where the "cuisine" field // has a value of "American" filter := bson.D{{"cuisine", "American"}} // Retrieves and prints the estimated number of documents in the collection estCount, estCountErr := coll.EstimatedDocumentCount(context.TODO()) if estCountErr != nil { panic(estCountErr) } // Retrieves and prints the number of matching documents in the collection count, err := coll.CountDocuments(context.TODO(), filter) if err != nil { panic(err) } // When you run this file, it should print: // Estimated number of documents in the movies collection: 25359 // Number of restaurants with American cuisine: 6183 fmt.Printf("Estimated number of documents in the restaurants collection: %d\n", estCount) fmt.Printf("Number of restaurants with American cuisine: %d\n", count) } ``` -------------------------------- ### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/change-streams Inserts sample course documents into the 'courses' collection. The server implicitly creates the database and collection if they do not exist. ```go coll := client.Database("db").Collection("courses") docs := []any{ Course{Title: "World Fiction", Enrollment: 35}, Course{Title: "Abstract Algebra", Enrollment: 60}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Initialize Go Project for AWS Lambda Source: https://www.mongodb.com/docs/drivers/go/current/connect/go-lambda Create a new Go project directory and initialize Go Modules. This sets up your project for AWS Lambda and MongoDB dependencies. ```bash mkdir lambdaexample cd lambdaexample go mod init lambdaexample ``` -------------------------------- ### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/project Inserts sample documents into the 'courses' collection. The driver implicitly creates the database and collection if they do not exist. ```go coll := client.Database("db").Collection("courses") docs := []any{ Course{Title: "Primate Behavior", CourseId: "PSY2030", Enrollment: 40}, Course{Title: "Revolution and Reform", CourseId: "HIST3080", Enrollment: 12}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Insert Sample Course Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/distinct Inserts sample course documents into the 'courses' collection. The server implicitly creates the database and collection if they don't exist. ```go coll := client.Database("db").Collection("courses") docs := []any{ Course{Title: "World Fiction", Department: "English", Enrollment: 35}, Course{Title: "Abstract Algebra", Department: "Mathematics", Enrollment: 60}, Course{Title: "Modern Poetry", Department: "English", Enrollment: 12}, Course{Title: "Plate Tectonics", Department: "Geology", Enrollment: 30}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Enable Compression via ClientOptions Source: https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/network-compression Configure compression algorithms by passing a string array of supported compressors to the `SetCompressors()` method on a `ClientOptions` instance. ```go opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"}) client, _ := mongo.Connect(opts) ``` -------------------------------- ### Run 'explain' Command for 'count' Operation Source: https://www.mongodb.com/docs/drivers/go/current/run-command Execute the 'explain' command with 'queryPlanner' verbosity to understand how a 'count' operation on the 'flowers' collection would run. This demonstrates constructing a nested command document. ```go db := client.Database("db") // Creates commands to count documents in a collection and explain // how the count command runs countCommand := bson.D{{"count", "flowers"}} explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}} // Retrieves results of the explain command var result bson.M err = db.RunCommand(context.TODO(), explainCommand).Decode(&result) ``` -------------------------------- ### Example Log Output (logrus JSONFormatter) Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/logging Example JSON-formatted console output showing debug-level logs for command events when using `logrus` with `JSONFormatter`. ```console { "command": "{\"insert\": \"testColl\", ...}", "commandName": "insert", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "insert", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" } { "command": "{\"delete\": \"testColl\", ...}", "commandName": "delete", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "delete", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" } ``` -------------------------------- ### Enable Logging on Client Creation Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/logging Configure a logger with debug level for commands and apply it to client options before connecting. Ensure the `uri` variable is defined. ```go loggerOptions := options. Logger(). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions) client, err := mongo.Connect(clientOptions) ``` -------------------------------- ### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/compound-operations Inserts multiple sample course documents into the 'courses' collection. The database and collection are implicitly created if they don't exist. ```go coll := client.Database("db").Collection("courses") docs := []any{ Course{Title: "Representation Theory", Enrollment: 40}, Course{Title: "Early Modern Philosophy", Enrollment: 25}, Course{Title: "Animal Communication", Enrollment: 18}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Example Aggregation Response Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application This is an example of the JSON response received after running the aggregation pipeline. It shows the count of comedy movies per year, sorted by count. ```json [ { " _id ": 2014, " count ": 287 }, { " _id ": 2013, " count ": 286 }, { " _id ": 2009, " count ": 268 }, { " _id ": 2011, " count ": 263 }, { " _id ": 2006, " count ": 260 }, ... ] ``` -------------------------------- ### Example JSON Output Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/text This is an example of the JSON output format you can expect after running the Go aggregation pipeline. It includes the 'name' and 'score' fields for each matching document. ```json {"name":"Green Curry","score":0.8999999999999999} {"name":"Kale Tabbouleh","score":0.5625} {"name":"Shepherd's Pie","score":0.5555555555555556} ``` -------------------------------- ### Install GJSON for JSON Parsing Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Install the GJSON library to efficiently parse JSON responses from AWS Bedrock. This is required for extracting the embedding data from the response body. ```sh go get github.com/tidwall/gjson ``` -------------------------------- ### Initialize MongoDB Client Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock Create methods to initialize the MongoDB client, including setting up Server API version and applying the connection URI. ```go func newDBClient(uri string) (*mongo.Client, error) { serverAPI := options.ServerAPI(options.ServerAPIVersion1) opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI) client, err := mongo.Connect(opts) if err != nil { return nil, err } return client, nil } func (app *App) Close() { if err := app.client.Disconnect(context.Background()); err != nil { panic(err) } } ``` -------------------------------- ### Install azidentity Module for Azure Source: https://www.mongodb.com/docs/drivers/go/current/security/authentication/oidc Install the azidentity module to fetch authentication credentials for other Azure environments like Azure Functions, ASE, or AKS. This module is required for custom OIDC callbacks in these environments. ```sh go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### CommandFailedEvent Example Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring Sample output for a CommandFailedEvent, indicating a command that did not succeed. ```none *event.CommandFailedEvent { "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": null, "Failure": "..." } ``` -------------------------------- ### Insert Sample Data into Collection Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/count Inserts multiple sample `Tea` documents into the `tea` collection. The driver implicitly creates the database and collection if they don't exist. ```go coll := client.Database("db").Collection("tea") docs := []any{ Tea{Type: "Masala", Rating: 10}, Tea{Type: "Matcha", Rating: 7}, Tea{Type: "Assam", Rating: 4}, Tea{Type: "Oolong", Rating: 9}, Tea{Type: "Chrysanthemum", Rating: 5}, Tea{Type: "Earl Grey", Rating: 8}, Tea{Type: "Jasmine", Rating: 3}, Tea{Type: "English Breakfast", Rating: 6}, Tea{Type: "White Peony", Rating: 4}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Example Output for DeleteMany() Source: https://www.mongodb.com/docs/drivers/go/current/crud/delete This is the expected output when the DeleteMany() operation successfully deletes documents. ```text Documents deleted: 6 ``` -------------------------------- ### ConnectionCreated Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionCreated` event. It is emitted when a new connection is established. ```none *event.PoolEvent { "type": "ConnectionCreated", "address": "...", "connectionId": 1, "options": null, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### ConnectionPoolClosed Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionPoolClosed` event. It is emitted before the server instance is destroyed. ```none *event.PoolEvent { "type": "ConnectionPoolClosed", "address": "...", "connectionId": 0, "options": null, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### Run 'hello' Command with RunCommand() Source: https://www.mongodb.com/docs/drivers/go/current/run-command Use `RunCommand()` to execute the 'hello' command and decode its response. This method is suitable for commands that return a single result document. ```go command := bson.D{{"hello", 1}} var result bson.M err = db.RunCommand(context.TODO(), command).Decode(&result) ``` -------------------------------- ### ConnectionPoolCleared Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionPoolCleared` event. It signifies that all connections in the pool have been closed. ```none *event.PoolEvent { "type": "ConnectionPoolCleared", "address": "...", "connectionId": 0, "options": null, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### ConnectionPoolReady Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionPoolReady` event. It indicates that the connection pool is ready for use. ```none *event.PoolEvent { "type": "ConnectionPoolReady", "address": "...", "connectionId": 0, "options": null, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### Initialize Application with AWS Configuration Source: https://www.mongodb.com/docs/drivers/go/current/integrations/vector-search-bedrock A constructor function that initializes the AWS configuration and creates a Bedrock client. It handles potential errors during AWS configuration loading. ```go func NewApp(ctx context.Context) (*App, error) { cfg, err := connectToAWS(ctx) if err != nil { log.Println("ERR: Couldn't load default configuration. Have you set up your AWS account?", err) return nil, err } bedrockClient := bedrockruntime.NewFromConfig(*cfg) return &App{ config: cfg, bedrock: bedrockClient, }, nil } ``` -------------------------------- ### ConnectionPoolCreated Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionPoolCreated` event. It includes details about the pool's configuration. ```none *event.PoolEvent { "type": "ConnectionPoolCreated", "address": "...", "connectionId": 0, "options": { "maxPoolSize": 100, "minPoolSize": 0, "maxIdleTimeMS": 0 }, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### ConnectionReady Event Data Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring This is an example of the data structure for a `ConnectionReady` event. It indicates that a connection has completed its handshake and is ready for operations. ```none *event.PoolEvent { "type": "ConnectionReady", "address": "...", "connectionId": 1, "options": null, "reason": "", "serviceId": null, "error": null } ``` -------------------------------- ### Upsert Operation Output Source: https://www.mongodb.com/docs/drivers/go/current/crud/update/upsert Example output showing the results of an upsert operation where no document matched the filter, leading to an insertion. ```none Number of documents updated: 0 Number of documents upserted: 1 ``` -------------------------------- ### Run Go Application Source: https://www.mongodb.com/docs/drivers/go/current/get-started Command to execute the Go application from the command line. Ensure your Go environment is set up. ```bash go run main.go ``` -------------------------------- ### Enable TLS using ClientOptions Source: https://www.mongodb.com/docs/drivers/go/current/security/tls Pass an empty `tls.Config` struct to the `SetTLSConfig()` method when creating a `ClientOptions` instance to enable TLS. This provides more granular control over TLS configuration. ```go uri := "" opts := options.Client().ApplyURI(uri).SetTLSConfig(&tls.Config{}) client, _ := mongo.Connect(opts) ``` -------------------------------- ### Subscribe to Command Events Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/monitoring Subscribe to CommandStartedEvent by instantiating a CommandMonitor and connecting to a deployment. This allows you to capture details about when commands start. ```go var eventArray []*event.CommandStartedEvent cmdMonitor := &event.CommandMonitor{ Started: func(ctx context.Context, e *event.CommandStartedEvent) { eventArray = append(eventArray, e) }, } clientOpts := options.Client().ApplyURI(uri).SetMonitor(cmdMonitor) client, err := mongo.Connect(clientOpts) ``` -------------------------------- ### Insert Sample Book Data into MongoDB Source: https://www.mongodb.com/docs/drivers/go/current/crud/delete Loads sample book data into the 'books' collection for demonstration purposes. The collection and database are implicitly created if they do not exist. ```go coll := client.Database("db").Collection("books") docs := []any{ Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}, Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Insert Sample Data Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/text Loads sample dish data into the 'menu' collection. The server implicitly creates the database and collection if they don't exist. ```go coll := client.Database("db").Collection("menu") docs := []any{ Dish{Name: "Shepherd’s Pie", Description: "A vegetarian take on the classic dish that uses lentils as a base. Serves 2."}, Dish{Name: "Green Curry", Description: "A flavorful Thai curry, made vegetarian with fried tofu. Vegetarian and vegan friendly."}, Dish{Name: "Herbed Whole Branzino", Description: "Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4."}, Dish{Name: "Kale Tabbouleh", Description: "A bright, herb-based salad. A perfect starter for vegetarians and vegans."}, Dish{Name: "Garlic Butter Trout", Description: "Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2."}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Expected JSON Output for Inserted Document Source: https://www.mongodb.com/docs/drivers/go/current/monitoring-and-logging/change-streams This is an example of the JSON output you can expect when a new document is inserted and the change stream captures the 'fullDocument'. ```json // results truncated { "_id": ..., "name": "8282", "cuisine": "Korean" } ``` -------------------------------- ### Insert Sample Data - Go Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/query-document Loads sample `Tea` documents into the `tea` collection. The `omitempty` struct tag omits fields if they are empty. ```go type Tea struct { Type string Rating int32 Vendor []string `bson:"vendor,omitempty" json:"vendor,omitempty"` } coll := client.Database("db").Collection("tea") docs := []any{ Tea{Type: "Masala", Rating: 10, Vendor: []string{"A", "C"}}, Tea{Type: "English Breakfast", Rating: 6}, Tea{Type: "Oolong", Rating: 7, Vendor: []string{"C"}}, Tea{Type: "Assam", Rating: 5}, Tea{Type: "Earl Grey", Rating: 8, Vendor: []string{"A", "B"}}, } result, err := coll.InsertMany(context.TODO(), docs) ``` -------------------------------- ### Example Aggregation Pipeline Source: https://www.mongodb.com/docs/drivers/go/current/crud/tutorial-web-application This JSON represents an aggregation pipeline that counts comedy movies by year. It includes stages for matching, grouping, and sorting. ```json [ {" $match ": {" genres ": "Comedy"}}, {" $group ": { " _id ": " $year ", " count ": {" $sum ": 1} }}, {" $sort ": {" count ": -1}} ] ``` -------------------------------- ### Estimate Document Count in Go Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/count Use EstimatedDocumentCount() to get an approximate number of documents in a collection. This method is faster than CountDocuments() but less precise. ```go count, err := coll.EstimatedDocumentCount(context.TODO()) if err != nil { panic(err) } fmt.Printf("Estimated number of documents in the tea collection: %d\n", count) ``` -------------------------------- ### Configure Connection Pool with Connection String Source: https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/connection-pools Use connection string parameters like `maxPoolSize`, `minPoolSize`, and `maxIdleTimeMS` to configure the connection pool. The `maxPoolSize` limits the number of connections, `minPoolSize` sets the initial number of connections, and `maxIdleTimeMS` defines how long a connection can remain idle before being closed. ```go // Connection string with connection pool options const uri = "mongodb://localhost:27017/?maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=30000" ``` ```go // Creates a new client and connects to the server client, err := mongo.Connect(options.Client().ApplyURI(uri)) ``` -------------------------------- ### Estimated Count with EstimatedDocumentCount() Source: https://www.mongodb.com/docs/drivers/go/current/crud/query/count Use the `EstimatedDocumentCount()` method to get a quick estimate of the number of documents in a collection by using the collection's metadata. ```APIDOC ## EstimatedDocumentCount() ### Description Estimates the number of documents in a collection using its metadata. This method is faster than `CountDocuments()` as it does not scan the collection. ### Method `EstimatedDocumentCount(context.Context) (int64, error)` ### Parameters None ### Request Example ```go count, err := coll.EstimatedDocumentCount(context.TODO()) ``` ### Response #### Success Response (int64) - **count** (int64) - The estimated number of documents in the collection. #### Error Response (error) - **error** - An error if the operation fails. ```