【问题标题】:Count subquery in a select - mongoDB在选择中计算子查询 - mongoDB
【发布时间】:2013-08-27 19:51:51
【问题描述】:

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

【问题讨论】:

标签: mysql node.js mongodb mongoose nosql


【解决方案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
)

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2022-01-24
    • 2015-11-11
    相关资源
    最近更新 更多