Home > Enterprise >  MongoDB - Filter and update multi nested data
MongoDB - Filter and update multi nested data

Time:02-17

I am trying to delete one nested document.

mycol = mongodb["structure"]

mycol.update_one(
    { "name" : "New Folder" },
    {"$pull" : {"structure.$.values" : {"report_name": "Area test"}}}
)

MongoDB data:

[{
    "structure":  [
        {
            "name": "New Folder",
            "values": [
            {
                "report_name": "Area test",
                "report_heading": "Area test",
            },
            {
                "report_name": "multi same",
                "report_heading": "multi same",
            },
            
            ]
        }
    ]
}]

I am using the above code to delete one document from the nested object. But my above query not working. Please take a look.

Expected result:

[{
    "structure":  [
        {
            "name": "New Folder",
            "values": [
            {
                "report_name": "multi same",
                "report_heading": "multi same",
            },
            ]
        }
    ]
}]

CodePudding user response:

Your document consists of structure array. To do updating the multi-nested document, you need $[<identifier>] filtered positional operator.

db.collection.update({
  "structure.name": "New Folder"
},
{
  "$pull": {
    "structure.$[structure].values": {
      "report_name": "Area test"
    }
  }
},
{
  arrayFilters: [
    {
      "structure.name": "New Folder"
    }
  ]
})

Sample Mongo Playground

  • Related