在select-mongoDB中计数子查询

我想做一个查询,以获得更多的推特在我的数据库mongoDB中的用户排名:

var TeewtSchema = new Schema({ userId: Number, twweetId : Number, createdAt: Date, cuerpo: String, nameUser: String, location: String, avatar: String, user: String }); 

MySql输出类似于:

  SELECT *, (SELECT COUNT(*) FROM `TABLE 1` WHERE userId = t.userId ) rank FROM `TABLE 1` t GROUP BY t.userId ORDER BY rank DESC 

但在mongoDB我不知道该怎么做

是的,正如JohnnyHK所build议的那样,你应该使用这个聚合框架 。 像下面的东西应该这样做:

 db.collection.aggregate( { $group : { _id : "$userId", numTweets = { $sum : 1 } }, // sum tweets over each user { $sort : { numTweets : -1 } } // sort by numTweets in descending order )