我有这种查询要运行。当键不存在时,手动运行此查询返回 OK,upsertedCount = 1
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
编辑:
将模式大小写更改为 Upper,以遵循 go 代码
使用更简单的代码版本
白板的微信
相关分类