2

我想进行查询以获得在我的数据库 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 我不知道该怎么做

4

1 回答 1

1

是的,正如 JohnnyHK 所建议的,您应该为此使用聚合框架。应该这样做:

db.collection.aggregate(
   { $group : { _id : "$userId", numTweets = { $sum : 1 } }, // sum tweets over each user
   { $sort : { numTweets : -1 } } // sort by numTweets in descending order
)
于 2013-09-19T18:23:54.527 回答