enter code hereI"m currently working on a rails app running mongodb via mongoid. Let's say I have two collections , posts and comments, and they're linked by a HABTM relation, I'd like to select the posts that have the most comments, and I think the way to do it is to count the comments for each post and order by comments.count DESC. I don't know how to count the number of comments for each posts, add a column to the posts results like count(comments) AS comments_count
in SQL, and order by this "pseudo-field".
Any thoughts on this ?
Thanks
EDIT, looking at the others answers related to this, I've tried:
db.posts.aggregate([
{ $group: {
_id: { post_id: '$post_id', comment_id: '$comment_id' }
}},
{ $group: {
_id: '$_id.post_id',
comments_count: { $sum: 1 }
}}]
, function(err, result){
console.log(result);
}
);
I'm getting
{
"result" : [{
"_id" : null,
"datasets_count" : 1
}],
"ok" : 1
}