您能告诉我如何计算状态为person的totalp吗?
这是我的密码
https://mongoplayground.net/p/d2Bmk4srq0O

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

  }
})

我想统计所有状态p的文档
预期产出。像那样的东西
[
  {
    "_id": "THBS",
    "totalAttendance": 10
  },
  {
    "_id": "HUAWEI",
    "totalAttendance": 2
  }
]

最佳答案

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

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

MongoPlayground

07-28 09:37