Get posts with n latest comments in MongoDB Get posts with n latest comments in MongoDB mongoose mongoose

Get posts with n latest comments in MongoDB


If you're using MongoDB 3.6 or higher you can use $lookup with custom pipeline to "join" posts with comments and take 2 most recent ones (using $limit)

db.posts.aggregate([    {        $sort: { date: -1 }    },    {        $limit: 8    },    {        $lookup: {            from: "comments",            let: { postId: "$_id" },            pipeline: [                { $match: { $expr: { $eq: [ "$$postId", "$post_id" ] } } },                { $sort: { date: -1 } },                { $limit: 2 }            ],            as: "comments"        }    }])