Weq Iou
Weq Iou

Reputation: 243

How to update value object into array in MongoDB Golang?

I am trying to update my addresses into my person data:

if _, ok := update["addressName"]; ok {
  request = bson.M{"addresses": bson.M{"addressName": update["addressName"]}}
} else {
  request = update
}
_, err = people.UpdateOne(context.TODO(), filter, bson.M{"$set": request})

this doesn't create an object in the array,

I want to have a result like this:

{
 "updateAt": TIME_NOW
 "addresses": [
    {"addressName": "ONLY", default: true},
    {"addressName": "ONLY", default: true}
 ]
}

how is the correct way to request for an object in array with MongoDB Driver?

Upvotes: 1

Views: 1519

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51497

You are $setting the addresses to an array containing a single element. Either you have to set the addresses to an array containing all the elements you need, or you have to add to that array using $push:

_, err = people.UpdateOne(context.TODO(), filter, bson.M{"$push":bson.M{"addresses":bson.M{ address info }})

Upvotes: 2

Related Questions