Reputation: 98
I want to convert my existing code to mongoDB aggregation framework. Here's my code that I want to convert in aggregation.
const comments = await Comments.find({post:req.params.id})
.populate({
path:"comments",
populate:{
path:"author",
select:"name photo"
},
select:{
createdAt:1,
author:1,
_id:1,
body:1,
likes:1
}
})
.populate("author","photo name")
.select({
createdAt:1,
author:1,
_id:1,
body:1,
comments:1,
likes:1
})
.sort("-createdAt");
Upvotes: 4
Views: 815
Reputation: 46481
You can use below aggregation
Comments.aggregate([
{ "$match": { "post": mongoose.Types.ObjectId(req.params.id) } },
{ "$sort": { "createdAt": -1 } },
{
"$lookup": {
"from": Comment.collection.name,
"let": { "comments": "$comments" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$_id", "$$comments"] } } },
{
"$lookup": {
"from": Author.collection.name,
"let": { "author": "$author" },
"pipeline": [{ "$match": { "$expr": { "$eq": ["$_id", "$$author"] } } }, { "$project": { "name": 1, "photo": 1 } }],
"as": "author"
}
},
{ "$unwind": "$author" },
{ "$project": { "createdAt": 1, "author": 1, "_id": 1, "body": 1, "likes": 1 } }
],
"as": "comments"
}
},
{
"$lookup": {
"from": Author.collection.name,
"let": { "author": "$author" },
"pipeline": [{ "$match": { "$expr": { "$eq": ["$_id", "$$author"] } } }, { "$project": { "name": 1, "photo": 1 } }],
"as": "author"
}
},
{ "$unwind": "$author" },
{
"$project": {
"createdAt": 1,
"author": 1,
"body": 1,
"comments": 1,
"likes": 1
}
}
])
Upvotes: 3