【问题标题】:Get multiple counts based on multiple conditions in MongoDB在 MongoDB 中根据多个条件获取多个计数
【发布时间】:2018-03-27 09:46:53
【问题描述】:

我想运行多个查询来获取 MongoDB 集合的计数。比如,我想运行一个查询来找出未决状态用户和已完成状态用户。像这样,有没有办法在查询/聚合中编写这两个条件并在 MongoDB 中获取单独的结果?

我的要求是,

我需要获取今天、昨天、上周和上个月的状态未决、已完成和打开的用户数。

我需要像这样的不同状态计数,

{
 "today": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "yesterday": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "lastWeek": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "lastMonth": {
    "pending": 10,
    "completed": 13,
    "open": 5
  }
}

【问题讨论】:

    标签: node.js database mongodb


    【解决方案1】:

    您可以为此使用聚合 $group 阶段:

    db.Collection.aggregate([
        {$project: {
            // If your pending/completed field is set to 1 or true
            pending: {$cond: [{$eq: ["$pending", 1 /* or true */]}, 1, 0]},
            completed: {$cond: [{$eq: ["$completed", 1 /* or true */]}, 1, 0]}
        }},
        {$group: {
            _id: //what you want,
            pending: {$sum: "$pending"},
            completed: {$sum: "$completed"}
        }}
    ]);
    

    【讨论】:

    • 我已经更新了这个问题。我认为您的查询是正确的,但要获得上述结果,我需要为四个时间戳查询四次。有没有办法在一个查询中获得上述结果?
    • 不知道有没有解决办法,我从来没有和mongo按日期分组,根据你的需要尝试$match
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 2023-03-10
    • 2021-07-20
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多