Answer a question

I am trying to update/replace a mongodb document using a struct but i keep on getting 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

Answers

You should provide an update statement instead of a document as third parameter to the Collection.UpdateOne method. For example:

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

See more on the available update operators in the MongoDB docs (the keys begin with '$').

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐