Add two new fields inside the array object if conditions meet in mongodb collection

285 Views Asked by At
[
  {
    "Empname": "Doug",
    "Group": [
      {
        "Category": [
          {
            "Categoryid": 123,
            "Categoryname": "science"
          },
          {
            "Categoryid": 233,
            "Categoryname": "Maths"
          }
        ]
      }
    ]
  },
  {
    "Empname": "stark",
    "Group": [
      {
        "Category": [
          {
            "Categoryid": 123,
            "Categoryname": "science"
          },
          {
            "Categoryid": 144,
            "Categoryname": "language "
          }
        ]
      }
    ]
  }
]

Here I want to insert two fields if it meets the following conditions

{
  "Categoryid": 123,
  "Categoryname": "science"
}

output should be like

[
  {
    "Empname": "Doug",
    "Group": [
      {
        "Category": [
          {
            "Categoryid": 123,
            "Categoryname": "science"
            "CategoryLabel": "Hex",
            "CategoryCode": "Hex-D",
          },
          {
            "Categoryid": 233,
            "Categoryname": "Maths"
          }
        ]
      }
    ]
  },
  {
    "Empname": "stark",
    "Group": [
      {
        "Category": [
          {
            "Categoryid": 123,
            "Categoryname": "science",
            "CategoryLabel": "Hex",
            "CategoryCode": "Hex-D",
          },
          {
            "Categoryid": 144,
            "Categoryname": "language "
          }
        ]
      }
    ]
  }
]
1

There are 1 best solutions below

0
Yong Shun On

You need update with arrayFilters to meet the condition for Category array.

And with multi: true to update multiple documents.

db.collection.update({},
{
  $set: {
    "Group.$[].Category.$[category].CategoryLabel": "Hex",
    "Group.$[].Category.$[category].CategoryCode": "Hex-D"
  }
},
{
  arrayFilters: [
    {
      "category.Categoryid": 123,
      "category.Categoryname": "science"
    }
  ],
  multi: true
})

Sample Mongo Playground