Home > other >  MongoDB, Cannot use the part (...) of (...) to traverse the element when trying $pull on nested arra
MongoDB, Cannot use the part (...) of (...) to traverse the element when trying $pull on nested arra

Time:12-11

I am trying to $pull a certain document contained within a nested array, within another nested array.

The structure goes as follows:

*clubs{ "club_id",
       "players"[{"player_id": 123,
                 "comments": [{"_id": "id"}, 
                              {"_id": "id2"}]
                                             }]
      }

I am trying to use the below in mongosh:

db.clubs.updateOne({"players.player_id": 363205}, {$pull: {"players.comments": {"players.comments._id": "5c61f001-768c-11ed-892f-346f24b28bd0"}}})

But when I submit this I get the following error:

MongoServerError: Cannot use the part (comments) of (players.comments) to traverse the element ({players: ...

Can someone please lend a hand here and let me know where I am going wrong? I've had a similar query work earlier, however it was only on 1 nested array of documents, rather than a nested array in a document that itself is contained in a nested array. Thanks in advance! :)

CodePudding user response:

Update with $[<identifier>] filtered positional operator.

db.clubs.updateOne({
  "players.player_id": 363205
},
{
  $pull: {
    "players.$[player].comments": {
      "_id": "5c61f001-768c-11ed-892f-346f24b28bd0"
    }
  }
},
{
  arrayFilters: [
    {
      "player.player_id": 363205
    }
  ]
})

Demo @ Mongo Playground

  • Related