Reputation: 71
I have a schema below:
I want to get the 20 records with the highest number of views + likes, how do I do in mongoose?
Upvotes: 0
Views: 224
Reputation: 589
You can use project to get the number of likes and pipe it with another project and add the views and likes.
db.demo.aggregate([{
$project: {
likes: {
$size: "$likes"
},
views: 1,
}
}, {
$project: {
total: {
$add: [
"$likes", "$views"
]
}
}
},{
$sort : {
total : -1
}
},{
$limit : 20
}])
Upvotes: 1
Reputation: 1336
as I know there is no way to do that in one operation, but you could add a separate field with views + likes, and user sort desc + limit: 20
Upvotes: 0