Home > Enterprise >  Add and update child arrays value in Mongo db
Add and update child arrays value in Mongo db

Time:05-17

I want to add value in array of the following json structure in mongo db collection "Scdtls". I need to add value only where "Type": "Fees" and "IsCurrentVersion": true.

  {
    "_id": ObjectId("60e71243b484cf3ec22a6845"),
    "Item": "School",
    "Text": "School Details",
    "Types": [
      {
        "Type": "Library",
        "Values": [
          {
            "IsCurrentVersion": false,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814f"),
                "Value": "Physics"
              }
            ]
          }
        ]
      },
      {
        "Type": "Fees",
        "Values": [
          {
            "IsCurrentVersion": false,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814f"),
                "Value": "Admission"
              },
              {
                "_id": ObjectId("611a4f113800d6af3fc4814k"),
                "Value": "Canteen"
              }
            ]
          },
          {
            "IsCurrentVersion": true,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814g"),
                "Value": "Tution"
              }
            ]
          }
        ]
      }
    ]
  }

This is how I am trying

db.Scdtls.update({
  "Item": "School",
  "Types.Type": "Fees",
  "Types.Values.IsCurrentVersion": true
},
{
  "$push": {
    "Types.1.Values.$[].KeyWords": {
      "_id": ObjectId(),
      "Value": "Sports"
    }
  }
})

But it is also adding "Value": "Sports" in "Type" : "Fees" where "IsCurrentVersion": false. Not able to understand the reason.

CodePudding user response:

If I understand correctly, you can do the update you want using "arrayFilters", like this:

db.Scdtls.update({
  "Item": "School",
  "Types.Type": "Fees",
  "Types.Values.IsCurrentVersion": true
},
{
  "$push": {
    "Types.$[x].Values.$[y].KeyWords": {
      "_id": ObjectId("deadbeafcafebabec0deface"),
      "Value": "Sports"
    }
  }
},
{
  "arrayFilters": [
    { "x.Type": "Fees" },
    { "y.IsCurrentVersion": true }
  ]
})

Try it on mongoplayground.net.

  • Related