更新时间:2024-01-18 GMT+08:00
分享

完整示例

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() {
  // 构建认证凭证
    // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
    // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
    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,  
    }
  // 高可用 URI, 注意 SetDirect 设为 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,注意 SetDirect 设为 true
  //directUri := "mongodb://host:8635/?ssl=true"
  //clientOpts := options.Client().ApplyURI(highProxyUri)
  //clientOpts = clientOpts.SetTLSConfig(&tls.Config {
  // InsecureSkipVerify: true,
  //}).SetDirect(true).SetAuth(credential)
  // 连接实例
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    client, err := mongo.Connect(ctx, clientOpts)
    if err != nil {
       fmt.Println("mongo实例连接失败:", err)
       return
    }
  // Ping 主节点
    ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()err = client.Ping(ctx, readpref.Primary())
    if err != nil {fmt.Println("ping 主节点失败:",err)
       return
    }
  // 选择数据库和集合
    collection := client.Database("test").Collection("numbers")
  // 插入单条数据
    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("插入单条记录失败:",err)
      return
   }else {
      fmt.Println(oneRes)
   }
  // 批量插入多条数据
   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("批量插入失败:",err)
      return
   }else {
      fmt.Println(manyRes)
   }
}
分享:

    相关文档

    相关产品