我有这种查询要运行。当键不存在时,手动运行此查询将以upsertedCount = 1手动返回OK
db.test.update({Key: 'random-id'}, {$inc: {Version: 1}},{upsert: true})
我尝试将其转换为下面的mongodb golang版本
client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017/"))
coll := client.Database("test").Collection("test")
filter := bson.D{bson.E{"Key", "random-id"}}
docs := bson.D{bson.E{"$inc", bson.E{"Version", 1}}}
upsert := true
result, err := coll.UpdateOne(
context.TODO(),
filter, docs,
&options.UpdateOptions{Upsert: &upsert})
if err != nil {
panic(err)
}
fmt.Print(result)
不幸的是,此查询返回错误
multiple write errors: [{write errors: [{Cannot increment with non-numeric argument: {key: "Version"}}]}, {<nil>}]
为什么不起作用?似乎驱动程序试图增加它而不将其发送给mongo
编辑:
最佳答案
问题出在你的docs
值上。应该是有效的文件。如果其所有元素均有效,则 bson.D
是有效的文档。它具有一个带有$inc
键的元素,该元素的值也必须是有效的文档。 bson.E
不是文档,它是文档的元素。
将您的docs
更改为此:
docs := bson.D{bson.E{"$inc", bson.D{bson.E{"Version", 1}}}}
它将起作用。
如果顺序不重要(在您的情况下不重要),则可以使用
bson.M
对filter
和docs
进行建模,如下所示:filter := bson.M{"Key": "random-id"}
docs := bson.M{
"$inc": bson.M{"Version": 1},
}
这更加简单,清晰和直观。
另请注意,有一些选项的构建器。像这样安全,习惯和明确地获取
options.UpdateOptions
值:options.Update().SetUpsert(true)
关于mongodb - golang mongo-go-driver无法增加先前的nil值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61635886/