如何在mongo-go-driver中添加选项`writeConcern`?

时间:2018-10-12 10:39:01

标签: database mongodb go

我不明白如何使用mongo-go-driver

为MongoDB添加记录参数

示例请求

subselect

如何在c.client.Database(MONGO_DATABASE).Collection(*packet.ID).InsertMany(nil, packet.Item, opt) 中指定必要的参数?

1 个答案:

答案 0 :(得分:1)

基于mongo-go-driver的当前版本(0.0.16),可以设置一个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