Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update/Replace mongodb document using struct & mongodb/mongo-go-driver

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
like image 448
Madu Alikor Avatar asked Oct 06 '18 23:10

Madu Alikor


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

What would you use in your PUT method if you want to update a document that is matched with the filter?

MongoDB updateMany() method The updateMany() method updates all the documents that matches the given filter.

What is the difference between update and replace in MongoDB?

With replaceOne() you can only replace the entire document, while updateOne() allows for updating fields. Since replaceOne() replaces the entire document - fields in the old document not contained in the new will be lost. With updateOne() new fields can be added without losing the fields in the old document.


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

like image 141
nijm Avatar answered Sep 21 '22 13:09

nijm


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)
like image 41
Nicolas Gaborel Avatar answered Sep 18 '22 13:09

Nicolas Gaborel