MongoDB nested lookup with 3 levels and append new value to the result docs MongoDB nested lookup with 3 levels and append new value to the result docs mongoose mongoose

MongoDB nested lookup with 3 levels and append new value to the result docs


Since each post have multiple comments, after unwinding comments you need to group it together to form an array

UpdateI have updated the fetch approach a lil bit like the below.

  db.posts.aggregate([  {    $lookup: {      from: "comments",      localField: "_id",      foreignField: "postId",      as: "comments",          },      },  {    $unwind: "$comments",      },  {    $lookup: {      from: "replies",      localField: "comments._id",      foreignField: "commentId",      as: "replies",          },      },  {    $unwind: "$replies",      },  {    "$addFields": {      "replies.countOflikes": {        $size: {          $ifNull: [            "$replies.likes",            []          ]        }      },      "replies.isLiked": {        $cond: {          if: {            $eq: [              {                $size: {                  $filter: {                    input: "$replies.likes",                    as: "item",                    cond: {                      $eq: [                        "$$item",                        1//id of the user whom you wanna check if liked the reply                                              ]                    }                  }                }              },              0            ]          },          then: false,          else: true        }      }    }  },  {    $group: {      _id: "$comments._id",      postId: {        $first: "$_id"      },      body: {        $first: "$body"      },      "comments": {        $first: "$comments"      },      replies: {        $push: "$replies"      }    }  },  {    $addFields: {      "comments.replies": "$replies"    }  },  {    $group: {      _id: "$postId",      body: {        $first: "$body"      },      comments: {        $push: "$comments"      }    }  }])

Summary of the change

  1. Unwinded both comments and it's replies
  2. Added new fields for displaying isLiked and countOfLikes using addFields stage
  3. grouped twice to reform original structure of the data(first grouped by comments then posts)

https://mongoplayground.net/p/lymCfeIIy9j