Updated on 2026-08-04 GMT+08:00

Go

Scenarios

DDS allows you to perform data operations using Go. You can connect to a DB instance through an SSL connection or a non-SSL connection. SSL connections provide stronger security.

By default, SSL is disabled for new DDS instances. For details about how to enable SSL, see Configuring SSL.

This section describes how to connect to a cluster instance using Go.

Prerequisites

  1. Ensure that the ECS can communicate with the DDS instance. To test the connectivity to the instance's IP address and port, run the curl command:

    curl ip:port

    If the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." is displayed, they can communicate with each other.

  2. If SSL is enabled, you must download the root certificate and upload it to the ECS.

Configuring the Environment and Obtaining the Driver

To add the MongoDB Go driver using Go Modules, follow the steps below:

  1. Initialize the module (if go.mod has not been created).
    go mod init <module-name>
  2. Install the driver.

    Use go get to directly obtain a specified version of the driver. The command will automatically update go.mod and go.sum.

    go get go.mongodb.org/mongo-driver@v1.12.1

    If you need to declare the dependency manually, you can add the following line to your go.mod file:

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

    Then run go mod tidy to download the module.

  3. Import the driver packages in your Go code.
    import (
    "go.mongodb.org/mongo-driver/bson"    
    "go.mongodb.org/mongo-driver/mongo"    
    "go.mongodb.org/mongo-driver/mongo/options"    
    "go.mongodb.org/mongo-driver/mongo/readpref" 
    )

Enabling and Disabling SSL

//For HA connections, the readPreference options are as follows: primary (default) indicates that data is read from the primary node only. primaryPreferred indicates that the primary node is preferred. If the primary node is unavailable, data is read from secondary nodes.
// secondary indicates that data is read from secondary nodes only. If no secondary node is available, an error is reported. secondaryPreferred indicates that secondary nodes are preferred. If no secondary node is available, data is read from the primary node.
// Storing authentication usernames and passwords directly in code poses significant security risks. Store them in configuration files or environment variables (passwords should be stored in ciphertext and decrypted at runtime) to ensure security.
// In this example, the username and password are stored in environment variables. Before running this example, set the environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV according to your local environment.
username = System.getenv("EXAMPLE_USERNAME_ENV")
password = System.getenv("EXAMPLE_PASSWORD_ENV")
highProxyUri := fmt.Sprintf("mongodb://%v:%v@host1:8635,host2:8635/?authSource=admin&readPreference=secondaryPreferred",username,password)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOpts := options.Client().ApplyURI(highProxyUri)
client, err := mongo.Connect(ctx, clientOpts)
// Ping the primary node.
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()err = client.Ping(ctx)
if err != nil {
   fmt.Println("Failed to ping mongos:", err)
   return
}
// Select a database and collection.
collection := client.Database("test").Collection("numbers")
// Insert a single record.
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
if err != nil{
   fmt.Println("Failed to insert the single record:",err)
   return
}else {
   fmt.Println(res)
}
// Build authentication credentials.
// Storing authentication usernames and passwords directly in code poses significant security risks. Store them in configuration files or environment variables (passwords should be stored in ciphertext and decrypted at runtime) to ensure security.
// In this example, the username and password are stored in environment variables. Before running this example, set the environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV according to your local environment.
username = System.getenv("EXAMPLE_USERNAME_ENV")
password = System.getenv("EXAMPLE_PASSWORD_ENV")
credential := options.Credential{
  AuthMechanism: "SCRAM-SHA-1",
  AuthSource:    "admin",
  Username:      username,
  Password:      password,
}
// For an HA URI, ensure that SetDirect is set to false.
highProxyUri := fmt.Sprintf("mongodb://%v:%v@host1:8635,host2:8635/?authSource=admin&readPreference=secondaryPreferred",username,password)
clientOpts := options.Client().ApplyURI(highProxyUri)
clientOpts = clientOpts.SetTLSConfig(&tls.Config {
InsecureSkipVerify: true,
}).SetDirect(false).SetAuth(credential)
// For a direct-connection URI, ensure that SetDirect is set to true.
//directUri := "mongodb://host:8635/?ssl=true"
//clientOpts := options.Client().ApplyURI(highProxyUri)
//clientOpts = clientOpts.SetTLSConfig(&tls.Config {
// InsecureSkipVerify: true,
//}).SetDirect(true).SetAuth(credential)
// Connect to the instance.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
   fmt.Println("Failed to connect to the mongo instance:", err)
   return
}

ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()err = client.Ping(ctx)
if err != nil {fmt.Println("Failed to ping the mongos node:",err)
   return
}
// Select a database and collection.
collection := client.Database("test").Collection("numbers")
// Insert a single record.
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
oneRes, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
if err != nil{fmt.Println("Failed to insert the single record:",err)
   return
}else {
   fmt.Println(oneRes)
}
// Batch insert
ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
docs := make([]interface{}, 100)
for i := 0; i < 100; i++{
   docs[i] = bson.D{{"name", "name"+strconv.Itoa(i)}, {"value", i}}
}
manyRes, err := collection.InsertMany(ctx, docs)
if err != nil {
   fmt.Println("Batch insertion failed:",err)
   return
}else {
   fmt.Println(manyRes)
}