17

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

2 Answers 2

25

I believe the accepted answer did not work for me because I am using the go.mongodb.org/mongo-driver package. With this package, the syntax is even simpler:

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

collection.UpdateOne(ctx, filter, update)
Sign up to request clarification or add additional context in comments.

2 Comments

works like a charm on go.mongodb.org/mongo-driver
update := bson.D{{"$set", document}} works too
9

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 '$').

3 Comments

One doesn't use bson.M in mongo-go-driver. Please, look at this example
The example from my understanding just updates a root property on the document called pi? I wish to replace the whole document with a struct called payment how do i do that?
If you want to replace use ReplaceOne instead of UpdateOne

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.