Mad*_*kor 11 go mongodb mongodb-query
我正在尝试使用结构更新/替换 mongodb 文档,但我一直在获取 err: update document must contain key beginning with '$'
collection := r.client.Database(database).Collection(greetingCollection)
payment.MongoID = objectid.New()
filter := bson.NewDocument(bson.EC.String("id", payment.ID))
_, err := collection.UpdateOne(ctx, filter, payment)
return err
Run Code Online (Sandbox Code Playgroud)
Nic*_*rel 16
我相信接受的答案对我不起作用,因为我正在使用该go.mongodb.org/mongo-driver
软件包。有了这个包,语法就更简单了:
update := bson.M{
"$set": yourDocument,
}
collection.UpdateOne(ctx, filter, update)
Run Code Online (Sandbox Code Playgroud)
您应该提供更新语句而不是文档作为Collection.UpdateOne
方法的第三个参数。例如:
update := bson.NewDocument(
bson.EC.SubDocumentFromElements(
"$set",
bson.EC.Double("pi", 3.14159),
),
)
collection.UpdateOne(ctx, filter, update)
Run Code Online (Sandbox Code Playgroud)
在MongoDB 文档中查看有关可用更新运算符的更多信息(键以“$”开头)。