Update multiple object values inside array in MongoDB with different values without looping, but pure query

Viewed 63

I want to update this document in MongoDB

[
   {
      "persons" : [
         {
            "name":"Javier",
            "occupation":"teacher"
         },
         {
            "name":"Juliana",
            "occupation":"novelist"
         },
         {
            "name":"Henry",
            "occupation":"plumber"
         }
      ]
   }
]

let's say I have a global array variable that contains this

var peopleGlobalVar = [
   {
      "name":"Javier",
      "occupation":"gardener"
   },
   {
      "name":"Henry",
      "occupation":"postman"
   }
]

I want to update the document with the value in globalVar WITHOUT common javascript looping, so if the names match, the occupation value will change, and I'm looking for the "pure query" solution.

the code I expect:

collection.update(
   {},
   {
      $set: {
         // code ...
      }
   },
   {
   $arrayFilter: [
    {
      "elem.name": {
        $in: 
          $function : {
             body: function(updatedPeopleFromGlobalVariable){
                let names = [];
                updatedPeopleFromGlobalVariable.forEach(function(person){
                   names.push(person.name);
                return names;
             },
             args: peopleGlobalVar,
             lang:"js",
          }
      },
      "multi": true
    }
  ]
}
)

What the output should be

[
   {
      "persons" : [
         {
            "name":"Javier",
            "occupation":"gardener"
         },
         {
            "name":"Juliana",
            "occupation":"novelist"
         },
         {
            "name":"Henry",
            "occupation":"postman"
         }
      ]
   }
]

Anyone have the solution to this?

0 Answers
Related