【问题标题】:how to get simple count & group by in MongoDB?如何在 MongoDB 中获得简单的计数和分组?
【发布时间】:2022-01-19 23:07:36
【问题描述】:

假设我有一个包含两个类别的数据,例如 - 足球或篮球,其中足球值为 1,篮球值为 2,我们有以下数据:

_id    game
'1'      1
'2'      1
'3'      2
'4'      1
'5'      2

(数据包含 3 次足球和 2 次篮球)。 我想执行返回以下对象的聚合:

{
   footballCount: 3,
   basketballCount: 2
}

我想不出这样的聚合会导致这样的结构。 我该怎么做?

【问题讨论】:

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


【解决方案1】:

您可以针对不同的情况进行条件求和。

db.collection.aggregate([
  {
    $group: {
      _id: null,
      footballCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$game",
                1
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      basketballCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$game",
                2
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      }
    }
  }
])

这是Mongo playground 供您参考。

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 2023-03-06
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多