我正在嘗試使用結構更新/替換 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 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
我相信接受的答案對我不起作用,因為我正在使用該go.mongodb.org/mongo-driver
軟件包。有了這個包,語法就更簡單了:
update := bson.M{ "$set": yourDocument, } collection.UpdateOne(ctx, filter, update)

當年話下
TA貢獻1890條經驗 獲得超9個贊
您應該提供更新語句而不是文檔作為該Collection.UpdateOne
方法的第三個參數。例如:
update := bson.NewDocument(
? ? bson.EC.SubDocumentFromElements(
? ? ? ? "$set",
? ? ? ? bson.EC.Double("pi", 3.14159),
? ? ),
)
collection.UpdateOne(ctx, filter, update)
在MongoDB 文檔中查看有關可用更新運算符的更多信息(鍵以“$”開頭)。
- 2 回答
- 0 關注
- 360 瀏覽
添加回答
舉報
0/150
提交
取消