Search code examples
pythonmongodbpymongo

How can I remove a subdict in array in pymongo?


I currently having a MongoDB collection which look like this:

{
    "_id": {
        "$numberLong": "1234567890"
    },
    "playlists": [{
        "name": "ff",
        "author": {
            "$numberLong": "123456789"
        },
        "tracks": [{
            "name": "name1",
            "uri": "uri1",
            "duration": 100
        }, {
            "name": "name2",
            "uri": "uri2",
            "duration": 120
        }, ...
        ]
    }], ...
}

How can I remove the subdict that contains {"name": "name2"}? I tried

colletion.update_one({"_id" : 1234567890}, {"$unset" : {{"playlists" : {{{"name" : playlist}: {f"tracks.{str(track)}"} : 1}}}}})

but it didn't work. Thank you so much!


Solution

  • You need $pull operator. To remove the track document with { "name": "name2" } that is under playlist document ({ "name": "ff" }), you need to apply $[<identifier>] filtered positional operator and arrayFilters.

    db.collection.update({
      "_id": 1234567890
    },
    {
      "$pull": {
        "playlists.$[playlist].tracks": {
          "name": "name2"
        }
      }
    },
    {
      arrayFilters: [
        {
          "playlist.name": "ff"
        }
      ]
    })
    

    Sample Mongo Playground

    Pymongo

    colletion.update_one({
      "_id": 1234567890
    },
    {
      "$pull": {
        "playlists.$[playlist].tracks": {
          "name": "name2"
        }
      }
    },
    array_filters = [
    {
      "playlist.name": "ff"
    }
    ])