首页 > 解决方案 > 拆分为桶,并在每个桶上运行聚合

问题描述

我有一个聚合查询,它将我的数据分成桶。我想知道是否可以选择更多的聚合管道阶段,这些阶段将分别在每个存储桶上运行。

这是我的数据:

[
   {
      "entityId":1,
      "accountId":"X",
      "date":"2019-10-10"
   },
   {
      "entityId":2,
      "accountId":"X",
      "date":"2019-10-10"
   },
   {
      "entityId":3,
      "accountId":"Y",
      "date":"2019-10-10"
   },
   {
      "entityId":4,
      "accountId":"Y",
      "date":"2019-10-10"
   }
]

我正在将我的数据拆分为 accountId 存储桶,现在它看起来像这样 -

[
   {
      "accountId":"X",
      "results":[
         {
            "entityId":1,
            "date":"2019-10-10"
         }
      ]
   },
   {
      "accountId":"Y",
      "results":[
         {
            "entityId":3,
            "date":"2019-10-10"
         }
      ]
   }
]

我想分别在每个桶上继续聚合管道,并按“日期”对其余数据进行分组,所以它看起来像这样:

[
   {
      "accountId":"X",
      "results":[
         {
            "date":"2019-10-10",
            "results":[
               {
                  "entityId":1
               },
               {
                  "entityId":2
               }
            ]
         }
      ]
   },
   {
      "accountId":"Y",
      "results":[
         {
            "date":"2019-10-10",
            "results":[
               {
                  "entityId":3
               },
               {
                  "entityId":4
               }
            ]
         }
      ]
   }
]

我试图了解如何在先前 $bucket 的结果上使用 $bucket 步骤,但我遇到了麻烦..

提前致谢!

标签: mongodbmongodb-queryaggregation-framework

解决方案


推荐阅读