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

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)

  • 在 `go.mongodb.org/mongo-driver` 上工作就像一个魅力 (2认同)

nij*_*ijm 6

您应该提供更新语句而不是文档作为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 文档中查看有关可用更新运算符的更多信息(键以“$”开头)。

  • 如果你想替换使用 `ReplaceOne` 而不是 `UpdateOne` (3认同)