Updated on 2024-02-07 GMT+08:00

Complete Example

import (
"context"   
"crypto/tls"   
"fmt"  
"strconv"   
"time"

"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"   
)
func main() {
  //Construct an authentication credential.
    // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
    // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
    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,  
    }
  //HA URI. Note that SetDirect is set to false.
    highProxyUri := "mongodb://host1:8635,host2:8635/?ssl=true"
    clientOpts := options.Client().ApplyURI(highProxyUri)
    clientOpts = clientOpts.SetTLSConfig(&tls.Config {
    InsecureSkipVerify: true,
    }).SetDirect(false).SetAuth(credential)
  //URI of the direct connection. Note 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 an 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
    }
  //Ping the primary node.
    ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()err = client.Ping(ctx, readpref.Primary())
    if err != nil {fmt.Println ("Failed to ping the primary node: ",err)
       return
    }
  //Select a database and collection.
    collection := client.Database("test").Collection("numbers")
  //Insert a 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 a record: ",err)
      return
   }else {
      fmt.Println(oneRes)
   }
  // Import {0} records.
   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)
   }
}