【问题标题】:How to total Count in mongoDB?如何在mongoDB中计算总数?
【发布时间】:2020-01-17 00:06:27
【问题描述】:

您能否告诉我如何计算状态为pperson 总数。 这是我的代码 https://mongoplayground.net/p/d2Bmk4srq0O

db.collection.aggregate({
  $group: {
    _id: "$Department",
    totalAttendance: {
      $sum: "$Status"
    },

  }
})

我想统计所有状态为p的文档

预期输出。类似的东西

[
  {
    "_id": "THBS",
    "totalAttendance": 10
  },
  {
    "_id": "HUAWEI",
    "totalAttendance": 2
  }
]

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你需要把$sum$conditionally放在这里

    db.collection.aggregate([
      { "$group": {
        "_id": "$Department",
        "totalAttendance": {
          "$sum": {
            "$cond": [
              { "$eq": [{ "$ltrim": { "input": "$Status" } }, "P       "] },
              1,
              0
            ]
          }
        }
      }}
    ])
    

    MongoPlayground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2019-06-09
      • 2016-12-31
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多