Search code examples
pythonmongodbmongodb-querypymongo

MongoDB - Filter and update multi nested data


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",
            },
            ]
        }
    ]
}]

Solution

  • 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