【问题标题】:How add option `writeConcern` in mongo-go-driver?如何在 mongo-go-driver 中添加选项“writeConcern”?
【发布时间】:2019-03-17 13:56:29
【问题描述】:

我不明白如何使用mongo-go-driver为 MongoDB 添加录制参数

示例请求

c.client.Database(MONGO_DATABASE).Collection(*packet.ID).InsertMany(nil, packet.Item, opt)

如何在opt中指定必要的参数?

【问题讨论】:

  • 什么是“mongo-go-native”?
  • @AlexBlex 这个驱动用于 MongoDB(用于 golang)
  • github.com/mongodb/mongo-go-driver/blob/… 建议它从集合中获取 WC。试一试。看来驱动程序还很年轻,所以就文档而言,源代码是你最好的朋友。

标签: database mongodb go


【解决方案1】:

1.0 版

在MongoDB Go驱动生产版本中,您可以设置writeConcern如下:

import (    
    "go.mongodb.org/mongo-driver/mongo/options"     
    "go.mongodb.org/mongo-driver/bson"  
    "go.mongodb.org/mongo-driver/mongo"     
    "go.mongodb.org/mongo-driver/mongo/writeconcern" 
)

mongoURI := "mongodb://server:port/"
opts := options.Client().ApplyURI(mongoURI).SetWriteConcern(writeconcern.New(writeconcern.WMajority()))

client, err := mongo.NewClient(opts)
if err != nil {
    panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
    panic(err)
}

collection := client.Database("database").Collection("collection")

另见:

版本 0.0.16

使用mongo-go-driver,您可以设置write concern 选项,如下例所示:

import(
  "github.com/mongodb/mongo-go-driver/bson"
  "github.com/mongodb/mongo-go-driver/core/writeconcern"
  "github.com/mongodb/mongo-go-driver/mongo"
  "github.com/mongodb/mongo-go-driver/mongo/collectionopt"
)

// Example document 
document := bson.VC.DocumentFromElements(
                 bson.EC.SubDocumentFromElements(
                   "foo",
                   bson.EC.Int32("bar", 101),
                 ),
               )

// Set majority write concern
wMajority := writeconcern.New(writeconcern.WMajority())

database := client.Database("database")
collection := database.Collection("collection", collectionopt.WriteConcern(wMajority))

_, err = collection.InsertOne(context.Background(), document)

还可以使用W(int) 指定任意数量的mongod 实例。查看更多writeconcern/writeconcern.go

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多