The update function of mongo-go-driver can be called like this.
filter := bson.D{"username", username}
update := bson.D{{"$set",
bson.D{
{"name", person.Name},
},
}}
result, err := collection.UpdateOne(ctx, filter, update)
type Person struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Username string `json:"username,omitempty" bson:"username,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
}
But, I need to call the update function using the person
struct, without mentioning every field of person struct like this.
filter := bson.D{"username", username}
update := bson.D{{"$set", <<how to convert person struct to bson document?>>}}
result, err := collection.UpdateOne(ctx, filter, update)
How can I convert the person struct to bson document?
ReplaceOne
I think is what you're after:
// Use it's ID to replace
filter := bson.M{"_id": existing.ID}
// Create a replacement object using the existing object
replacementObj := existing
replacementObj.SomeFieldToChange = "new-replacement-object"
updateResult, err := coll.ReplaceOne(context.Background(), filter, replacementObj)
assertNotErr(t, err)
assertEquals(t, 1, int(updateResult.ModifiedCount))
A note that ErrNotFound is no longer thrown as it was in mgo - you have to check the Modified/Upserted count.
You could do something like this:
func Update(person Person) error {
pByte, err := bson.Marshal(person)
if err != nil {
return err
}
var update bson.M
err = bson.Unmarshal(pByte, &update)
if err != nil {
return
}
// NOTE: filter and ctx(Context) should be already defined
_, err = collection.UpdateOne(ctx, filter, bson.D{{Key: "$set", Value: update}})
if err != nil {
return err
}
return nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With