Update MongoDB array field in go

Viewed 228

I have this data schema:

"person": { "name": "Neeraj", "hobbies": ["movies" ] }

This is the struct to insert the document in MongoDB

type Person struct {
  Id   primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
  Name string `bson:"name,omitempty" json:"name,omitempty"`
  Hobbies []string `json:"hobbies,omitempty" bson:"hobbies,omitempty"`
}

When PUT person API is called without the hobbies field, I would expect it to not update the hobbies field in DB. In this case when I parse the body, the struct has Hobbies set as null and because of 'omitempty' bson tag, it does not update the hobbies field in DB, which is fine.

filter := bson.D{{"_id", oid}}
update := bson.M{
    "$set": record,
}
result, err := collection.UpdateOne(ctx, filter, update)

However, when PUT person API is called with the hobbies field set to an empty array, I would expect it to update the hobbies field and set it to empty. But in this case too, the record struct has hobbies field set to null, and it doesn't update the hobbies field.

How do I do this in go, so that my code caters to all of following update payload? I am using golang official mongo driver.

{
   "name": "john"  // Should not modify the hobbies field.
}

{
  "name": "john",
  "hobbies": []  // // Should update the hobbies field to an empty array
}
1 Answers

It sounds like you want to merge the person object based on what was provided in the request, whereas the MongoDB $set operator, "replaces the value of a field with the specified value." Because MongoDB doesn't understand how complex types should be merged, you'll have to specify the exact merging logic yourself.

filter := bson.M{"_id": oid}
set := bson.M{
    "name": record.Name,
}
if (record.Hobbies) != nil {
    set["hobbies"] = record.Hobbies
}
update := bson.M{"$set": set}
Related