tencent cloud

TencentDB for MongoDB

Go SDK

Unduh
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-06-11 11:36:11

Scenarios

Go is widely used in backend microservices and infrastructure development due to its high concurrency performance and fast compilation. The official MongoDB Go Driver provides type-safe APIs for database operations that integrate seamlessly with Go's concurrency model. This document walks you through a complete example of connecting to TencentDB for MongoDB using the official Go driver.

Prerequisites

You have created a TencentDB for MongoDB instance, and the instance status is Running.
You have prepared a CVM that resides in the same VPC as the MongoDB instance, and you have installed Go version 1.18 or later.

Installing a Driver

Note:
The early community-driven mgo (gopkg.in/mgo.v2) is no longer maintained. Use the official MongoDB Go Driver instead.
go get go.mongodb.org/mongo-driver/mongo
go.mod example:
module mongodb-demo

go 1.21

require go.mongodb.org/mongo-driver v1.13.1

Must-Knows

Context Usage: All operations in the Go driver accept a context.Context parameter to control timeouts and cancellation. In production environments, set a reasonable timeout for each operation.
Password Encoding: Use url.QueryEscape() to URL-encode the password and prevent special characters from causing parsing errors in the connection string.
Struct Mapping: Map Go struct fields to MongoDB document fields using bson tags. By default, mapped field names are converted to lowercase, so we recommend explicitly specifying the bson tag for each field.
Connection Reuse: mongo.Clienthas a built-in connection pool. Reuse the same instance throughout your application, typically by injecting it as a dependency into your handler functions.
Cursor Closing: Always call Close() on the Cursor returned by Find() after use. We recommend using a defer statement to ensure it is closed properly.

Connection and CRUD Operation Examples

package main

import (
"context"
"fmt"
"log"
"net/url"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)

// User defines the user document structure.
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Username string `bson:"username"`
Age int `bson:"age"`
Email string `bson:"email"`
CreatedAt time.Time `bson:"created_at"`
}

func main() {
// Connection URI (Replace with your actual connection information)
// If the password contains special characters, use url.QueryEscape() to encode it.
user := "mongouser"
password := url.QueryEscape("thepasswordA1")
host := "10.66.187.127:27017"
uri := fmt.Sprintf("mongodb://%s:%s@%s/admin", user, password, host)

// Replica set connection string (Recommended):
// uri := fmt.Sprintf("mongodb://%s:%s@IP1:27017,IP2:27017,IP3:27017/admin?replicaSet=cmgo-xxxxxxxx_0", user, password)

// Configure connection parameters
clientOpts := options.Client().
ApplyURI(uri).
SetMaxPoolSize(50). // Maximum size of the connection pool
SetMinPoolSize(5). // Minimum size of the connection pool
SetConnectTimeout(10 * time.Second). // Connection timeout
SetSocketTimeout(30 * time.Second). // Socket timeout
SetMaxConnIdleTime(60 * time.Second). // Idle connection timeout
SetRetryWrites(true). // Enable retryable writes
SetRetryReads(true) // Enable retryable reads

// Establish a connection.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
log.Fatalf("Connection failure: %v", err)
}
defer func() {
if err := client.Disconnect(context.Background()); err != nil {
log.Printf("Disconnection failure: %v", err)
}
fmt.Println("Connection closed")
}()

// Verify the connection
if err := client.Ping(ctx, readpref.Primary()); err != nil {
log.Fatalf("Ping failure: %v", err)
}
fmt.Println("Connection successful")

// Select a database and a collection.
collection := client.Database("mydb").Collection("users")

// ========== Insert a Document ==========
user1 := User{
Username: "jack",
Age: 31,
Email: "jack@example.com",
CreatedAt: time.Now(),
}
insertResult, err := collection.InsertOne(context.Background(), user1)
if err != nil {
log.Fatalf("Insertion failure: %v", err)
}
fmt.Printf("Inserted document ID: %v\\n", insertResult.InsertedID)

// Batch Insert
users := []interface{}{
User{Username: "alice", Age: 28, Email: "alice@example.com", CreatedAt: time.Now()},
User{Username: "bob", Age: 35, Email: "bob@example.com", CreatedAt: time.Now()},
}
insertManyResult, err := collection.InsertMany(context.Background(), users)
if err != nil {
log.Fatalf("Batch insertion failure: %v", err)
}
fmt.Printf("Batch inserted %d documents\\n", len(insertManyResult.InsertedIDs))

// ========== Query Documents ==========
var foundUser User
err = collection.FindOne(context.Background(), bson.M{"username": "jack"}).Decode(&foundUser)
if err != nil {
log.Fatalf("Query failure: %v", err)
}
fmt.Printf("Query a single document: %+v\\n", foundUser)

// Conditional Query (Age greater than 30)
cursor, err := collection.Find(context.Background(), bson.M{"age": bson.M{"$gt": 30}})
if err != nil {
log.Fatalf("Conditional query failure: %v", err)
}
defer cursor.Close(context.Background())

fmt.Println("Users with age greater than 30:")
for cursor.Next(context.Background()) {
var u User
if err := cursor.Decode(&u); err != nil {
log.Printf("Decoding failure: %v", err)
continue
}
fmt.Printf(" - %s, Age: %d\\n", u.Username, u.Age)
}

// ========== Update Documents ==========
updateResult, err := collection.UpdateOne(
context.Background(),
bson.M{"username": "jack"},
bson.M{"$set": bson.M{"age": 32}},
)
if err != nil {
log.Fatalf("Update failure: %v", err)
}
fmt.Printf("Updated %d documents\\n", updateResult.ModifiedCount)

// ========== Delete Documents ==========
deleteResult, err := collection.DeleteMany(
context.Background(),
bson.M{"username": bson.M{"$in": bson.A{"jack", "alice", "bob"}}},
)
if err != nil {
log.Fatalf("Deletion failure: %v", err)
}
fmt.Printf("Deleted %d documents\\n", deleteResult.DeletedCount)
}
Sample Output:
Connection successful
Inserted document ID: ObjectID("6789abcdef1234567890abcd")
Batch Insert 2 Documents
Query a single document: {ID:ObjectID("6789abcdef1234567890abcd") Username:jack Age:31 Email:jack@example.com CreatedAt:2026-04-17 15:00:00 +0800 CST}
Users with age greater than 30:
- jack, age: 31
- bob, age: 35
Update 1 Document
Delete 3 Documents
The connection has been closed.

FAQs

"server selection error: server selection timeout" Prompt During Connection

Error Message Example:
server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: 10.66.187.127:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1" }, ] }
Troubleshoot by following these steps:
1. Confirm that the authentication database is specified as admin in the URI.
// Correct: The URI path is /admin.
uri := "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin"

// Correct: Specify the authentication database via the authSource parameter when connecting to the business database.
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin"

// Error: When connecting to the business database without specifying authSource, the driver defaults to authenticating with the mydb database, causing authentication to fail.
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb"
2. Confirm that special characters in the password are URL-encoded: Use url.QueryEscape() to encode the password:
import "net/url"

password := url.QueryEscape("pass@123") // Output: pass%40123
uri := fmt.Sprintf("mongodb://mongouser:%s@10.66.187.127:27017/admin", password)
3. Confirm network connectivity: Run the following command on the CVM to verify whether the network is reachable:
telnet <MongoDB-instance-IP> 27017
The output Connected indicates that the network is reachable. Check the authentication configuration.
An output of Connection timed out indicates that the network is unreachable. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.

"context deadline exceeded" Prompt During Runtime

Error Message Example:
context deadline exceeded
This error indicates an operation timeout. The troubleshooting approach varies depending on the scenario in which it occurs:
Scenario 1: Connection timeout during the connection phase.
Check whether the SetConnectTimeout configuration is reasonable. In a private network environment, 10 seconds is sufficient:
clientOpts := options.Client().
ApplyURI(uri).
SetConnectTimeout(10 * time.Second)
Scenario 2: Timeout during the query or write phase.
Check whether the context timeout for the incoming operation is too short:
// Error: Timeout is too short. Complex queries may not be completed within 1 second.
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)

// Correct: Set a reasonable timeout based on business complexity.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

cursor, err := collection.Find(ctx, bson.M{"age": bson.M{"$gt": 30}})
Scenario 3: Timeout occurs after prolonged operation.
This may be caused by idle connections being closed by the server. Confirm the following configurations:
clientOpts := options.Client().
ApplyURI(uri).
SetMaxConnIdleTime(60 * time.Second). // Idle connections are closed after 60 seconds.
SetRetryWrites(true). // Enable retryable writes.
SetRetryReads(true) // Enable retryable reads

"cannot find module providing package go.mongodb.org/mongo-driver/..." Prompt During Compilation

Error Message Example:
cannot find module providing package go.mongodb.org/mongo-driver/mongo
Troubleshoot by following these steps:
1. Confirm that the Go module is initialized: In the project directory, confirm that the go.mod file exists. If it does not exist, execute the following:
go mod init <module-name>
2. Install the MongoDB Go Driver.
go get go.mongodb.org/mongo-driver/mongo
3. Execute go mod tidy to organize dependencies.
go mod tidy
After installation, confirm that the go.mod file contains the following dependencies:
require go.mongodb.org/mongo-driver v1.13.1

Is Using the Deprecated mgo Driver Feasible?

The community-driven mgo (gopkg.in/mgo.v2) was discontinued in 2018 and has the following limitations:
Comparison Item
mgo (Deprecated)
Official Go Driver
Maintenance Status
Not supported
Actively maintained
MongoDB version support
Up to 3.6
Supports versions 4.0 - 8.0
Context support
Not supported
Supported.
Transaction Support
Not supported
Supported.
Retryable Reads and Writes
Not supported
Supported.

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan