I have a Post
model that has a likes
array that contains the ObjectId
of the user that liked the Post, I would like to sort Posts based on how many likes they have received.
I'm sure I would use $size
, $sort
and aggregate
, but everything I have tried doesn't seem to work. Can you use $size
within $sort
? What would be the correct way of doing this? and is there a specific way of doing it with mongoose?
CodePudding user response:
db.collection.aggregate([
{
$set: {
size: { $size: "$likes" }
}
},
{
$sort: {
size: -1
}
}
])