您可以在 Mongo 的单个查询中对每个自定义过滤器应用多个聚合吗?

问题描述 投票:0回答:1

在 SQL 中,您可以执行多个聚合,每个聚合都有自己的条件,在单个查询中,如下所示:

SELECT   some_grouping_column,
         MAX(some_column WHERE some_flag is true),
         COUNT(some_other_column WHERE some_other_flag is false)
FROM     some_table
GROUP BY some_grouping_column

在 Mongo 中也可以吗?

mongodb aggregation-framework
1个回答
0
投票

是的,你可以做到。我创建了一个场景来计算 stackoverlfow 网站上的每个用户:

  1. 到目前为止他们给出的答案总数。
  2. 他们的回答获得的总票数,
  3. 他们的所有答案都获得了最高票数:

我为此使用了多个聚合器:

这是 Json :

[
  {
    "username": "Stack Overflow User1",
    "votes": 5,
    "answer": true,
    "question": false
  },
  {
    "username": "Stack Overflow User2",
    "votes": 10,
    "answer": true,
    "question": false
  },
  {
    "username": "Stack Overflow User1",
    "votes": 5,
    "answer": false,
    "question": true
  },
  {
    "username": "Stack Overflow User1",
    "votes": 8,
    "answer": true,
    "question": false
  },
  {
    "username": "Stack Overflow User2",
    "votes": 7,
    "answer": true,
    "question": false
  }
]

这是具有多个聚合器条件的查询:

db.collection.aggregate([
  {
    $group: {
      _id: "$username",
      answer_count: {
        $sum: {
          $cond: [
            "$answer",
            1,
            0
          ]
        }
      },
      total_votes: {
        $sum: {
          $cond: [
            "$answer",
            "$votes",
            0
          ]
        }
      },
      max_votes: {
        $max: {
          $cond: [
            "$answer",
            "$votes",
            null
          ]
        }
      }
    }
  }
])

这是它的结果:

[
  {
    "_id": "Stack Overflow User2",
    "answer_count": 2,
    "max_votes": 10,
    "total_votes": 17
  },
  {
    "_id": "Stack Overflow User1",
    "answer_count": 2,
    "max_votes": 8,
    "total_votes": 13
  }
]

这是我尝试过的在线编辑器: https://mongoplayground.net/p/mYjI4L3e8wz

© www.soinside.com 2019 - 2024. All rights reserved.