Home > other >  How to query for a subdocument when only _id of the subdocument is given in mongoose?
How to query for a subdocument when only _id of the subdocument is given in mongoose?

Time:04-07

I have a snapshot of a document present in the database as shown below

{
        "_id" : ObjectId("624e105df043d4ad4ee893ee"),
        "title" : "First post",
        "author" : "Rituparna",
        "comments" : [
                {
                        "content" : "First comment",
                        "author" : "Ritu",
                        "_id" : ObjectId("624e109b966fbe64b2a80ea9"),
                        "replies" : [ ]
                },
                {
                        "content" : "second comment",
                        "author" : "Ritu",
                        "_id" : ObjectId("624e10a4e33f7962d0002f39"),
                        "replies" : [ ]
                }
        ],
        "__v" : 0
}

Now suppose that you are given only the _id of a commen, say the first comment 624e109b966fbe64b2a80ea9

The end result i am looking for is

{
    "content" : "First comment",
    "author" : "Ritu",
    "_id" : ObjectId("624e109b966fbe64b2a80ea9"),
    "replies" : [ ]
}

What query do I need to write when I am given only the _id of the comment and the Post model, that is the parent of the subdocument model ?

CodePudding user response:

db.collection.aggregate([
  {
    $match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
  },
  {
    $unwind: "$comments"
  },
  {
    $match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
  },
  {
    $replaceWith: "$comments"
  }
])

https://mongoplayground.net/p/WmeoKTg8tUS

  • Related