Update property of a nested object inside an array

I have this data structure

{
 {  "_id" : "628073739057102858",
   "company" : {
       "name" : "Unnamed Company",
       "funds" : 10000,
       "employees" : [ 
           {
               "name" : "Owen",
               "gender" : "Male",
               "pay" : 1378,
               "trait" : "Independent",
               "ips" : "14.0",
               "sales" : 0
           }
       ],
       "stats" : {
           "max_employees" : 2,
           "experience" : 0,
           "totalincome" : 0,
           "sales" : 0
       },
   },
   "__v" : 0

}

I was wonder how I could access the object inside of employees, such as Owen and set one of it’s properties.

For example I would like to set his sales properties to a different value, maybe something like 5.

Normally if this was in code I would just loop through the employees array to find the object property, for example:

employees.forEach( person => {
        if (person.name == "Owen"){
            // Do Something
        }
    })

However I have no clue how to achieve this as a MongoDB function. As normal I tried code snippets from stack-overflow and tried to skim through the documentation however I don’t seem to have any luck. Any help would be much appreciated.

1 Like

Hi @eitzen_N_A,

You will need to use array filters update with $[] opertors :
https://docs.mongodb.com/manual/reference/operator/update/positional-all/#update-nested-arrays-in-conjunction-with----identifier--

db.coll.update({}, { $set: { "employees.$[elem].sales": 2 } },   { arrayFilters: [  { "elem.name": "Owen" } ]})

Thanks
Pavel

1 Like

You’re a life saver, thanks Pavel!!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.