使用struct&mongodb / mongo-go-driver更新/替换mongodb文档

时间:2018-10-06 23:52:45

标签: mongodb go 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

2 个答案:

答案 0 :(得分:5)

我认为接受的答案对我不起作用,因为我使用的是go.mongodb.org/mongo-driver软件包。使用此软件包,语法更加简单:

update := bson.M{
        "$set": yourDocument,
    }

collection.UpdateOne(ctx, filter, update)

答案 1 :(得分:2)

您应该提供更新语句而不是文档作为Collection.UpdateOne方法的第三个参数。例如:

update := bson.NewDocument(
    bson.EC.SubDocumentFromElements(
        "$set",
        bson.EC.Double("pi", 3.14159),
    ),
)
collection.UpdateOne(ctx, filter, update)

查看MongoDB docs中可用的更新运算符的更多信息(键以'$'开头)。

相关问题