1

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?

1 Answer 1

2

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 }})
Sign up to request clarification or add additional context in comments.

14 Comments

I follow that but not work: here is the request request = bson.M{"$push":bson.M{"addresses":bson.M{ "addressName": update["addressName"] }}}
the address was null and then I update like your answer, it doesn't change, but after I $set array of data of it and then run your code , it was work, so is that mean we can't do like your syntax if that addresses in mongo null ?
I just tried as you said and it works. What version of mongodb are you using?
Is it null, or does it not exist? If it is null, it'll fail.
MongoDB shell version v4.2.7, mongo-driver 1.3.4, did you create person data ? and make on addresses null not empty array ? and then run your code? I was like that and nothing happen
|

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.