在select - mongoDB中计算子查询

时间:2013-08-25 03:00:05

标签: mysql node.js mongodb mongoose nosql

我想在我的数据库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中我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

是的,正如JohnnyHK建议的那样,你应该使用aggregation framework。像下面这样的东西应该这样做:

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