Home > Blockchain >  Using $pull to remove a grandchild element from document in mongo
Using $pull to remove a grandchild element from document in mongo

Time:04-02

As the title suggests, I have a document that contains an array of objects (comments) within an array of objects (notes). Users can comment on each note, but I'm also trying to add a delete function to remove the comments on each note.

scheduleCollection.update_one({'date': date},
                                             {'$pull': {"note.$": {"comment.$.commentId": commentId}}}):

This is what I currently have, but I'm receiving this error:

The positional operator did not find the match needed from the query., full error: {'index': 0, 'code': 2, 'errmsg': 'The positional operator did not find the match needed from the query.'}

I've tried various combinations within the $pull but haven't been successful.

The data structure looks something like:

{
"date": "03-31-2022",
"note": [{
   "comment": [{
      "commentId": "uuid",
      "comment": "etc"
      }]
   }]
}

CodePudding user response:

see if it helps:

{
"_id" : ObjectId("6247960b5b63591be3ddf3f9"),
"date" : ISODate("2022-04-01T21:17:15.570-03:00"),
"note" : [
    {
        "comment" : [
            {
                "commentId" : ObjectId("6247960b5b63591be3ddf3f8"),
                "comment" : "etc"
            }
        ]
    }
]},


db.pull.update(
{ 'note.comment.commentId': ObjectId("6247960b5b63591be3ddf3f8") },
{
    $unset: {
        "note.0.comment.0.comment": true
    }
},
{ multi: 1 })

{
"_id" : ObjectId("6247960b5b63591be3ddf3f9"),
"date" : ISODate("2022-04-01T21:17:15.570-03:00"),
"note" : [
    {
        "comment" : [
            {
                "commentId" : ObjectId("6247960b5b63591be3ddf3f8")
            }
        ]
    }
]}

OR:

db.pull.update(
{ 'note.comment.commentId': ObjectId("624799285b63591be3ddf3fd") },
{
    $pull:
        {
            note:
                {
                    comment: { $elemMatch: { commentId: { $eq: ObjectId("624799285b63591be3ddf3fd") } } }
                }
        }
})

CodePudding user response:

update_one({'note.comment.commentId': commentId},
                                         {'$pull': {'note.$.comment': {'commentId': {'$eq': commentId}}}}):

Was the solution that I came to.

  • Related