Home > Enterprise >  MongoDB - Add elements to sub array that meets the filter condition
MongoDB - Add elements to sub array that meets the filter condition

Time:06-17

Here is an example : example

I am trying to add 'X' and 'Y' only to the subcategory arrays that contains EDUCATION key. What is happening here is that it adds 'X' and 'Y' to all subcategory if at least on of them contains the EDUCATION key.

CodePudding user response:

You need to use arrayFilters, to match specific element in an array.

db.collection.update({},
{
  "$push": {
    "data.category.$[elem].subcategory": {
      "$each": [
        "X",
        "Y"
      ]
    }
  }
},
{
  multi: true,
  arrayFilters: [
    {
      "elem.subcategory": "EDUCATION"
    }
  ]
})

Check this link

  • Related