【问题标题】:count documents with multiple conditions in one query在一个查询中计算具有多个条件的文档
【发布时间】:2019-01-08 18:22:59
【问题描述】:

我正在尝试计算 mongoDB(使用 mongoose)中的数据库记录,其中记录的状态为待处理、已批准以及已拒绝。所以,我基本上是想得到一个结果,我可以显示每个计数并将其显示在我的视图中,即:

待定:35 批准:97 拒绝:12

我有这个,但它只算“待处理”。有没有办法在一个查询中计算所有 3 个,或者我需要运行 3 个单独的查询并为每个查询获取结果?

Product.countDocuments({status: 'pending', userId: req.session.user._id})
.then(pending => {
    if (!pending) {
        return next();
    }
    req.pending = pending;
    next();
})
.catch(err => {
    console.log(err);
});

编辑:在某种程度上,我已经设法做到了这一点,在控制台中我得到了所有结果的计数,但只需要弄清楚如何将每个结果放入它自己的变量中。

Product.aggregate([
   { $group: { _id: { status: "$status"}, totalStatus: {$sum: 1} } }
])
.then(function (res) {
    console.log(res);
    next();
  });

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    要在单个查询中查找多个计数,请使用 mongodb 聚合框架,它在多个阶段操作数据,您的问题已经得到解答,请访问下面的链接。我为您更新查询。 Multiple Counts with single query in mongodb

    Product.aggregate([
      { "$facet": {
        "Pending": [
          { "$match" : { "status": { "$exists": true, "$in":["pending"] }}},
          { "$count": "Pending" },
        ],
        "Approved": [
          { "$match" : {"status": { "$exists": true, "$in": ["approved"] }}},
          { "$count": "Approved" }
        ],
        "Rejected": [
          { "$match" : {"status": { "$exists": true, "$in": ["rejected"] }}},
          { "$count": "Rejected" }
        ]
      }},
      { "$project": {
        "Pending": { "$arrayElemAt": ["$Pending.Pending", 0] },
        "Approved": { "$arrayElemAt": ["$Approved.Approved", 0] },
        "Rejected": { "$arrayElemAt": ["$Rejected.Rejected", 0] }
      }}
    ])
    

    【讨论】:

    • 谢谢,但我想问的是如何使用 Mongoose 来做到这一点。
    • mongoose 也支持聚合功能。请参考以下链接。mongoosejs.com/docs/api.html#mongoose_Mongoose-Aggregate
    • 谢谢沙哈布。我确实看过那里,但我真的不明白如何适用于我的情况。我对猫鼬很陌生
    • 我厌倦了浓缩它并设法用一行几乎到达那里。请参阅我编辑的问题。你觉得这也合适吗? { $group: { _id: { status: "$status"}, totalStatus: {$sum: 1} } }
    • 查询看起来不错,您正在按状态对字段进行分组。如果它满足您的要求,请暂时使用它。
    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2021-11-23
    • 2022-11-17
    相关资源
    最近更新 更多