简体   繁体   English

mongo db如何执行两组

[英]mongo db how to performe two groups

I have the following document:我有以下文件:

{
 _ids : ...
 market : ...
 contractorName : ...
 field :...
 amount : ...
}

and i want to group it first by market then group the result by field (sum of amounts) inside each obtained list as follow:我想先按市场对其进行分组,然后按每个获得的列表中的字段(金额总和)对结果进行分组,如下所示:

{
 [
  market : ...
  result : [
            {
             field : ...
             sumOfAmounts : ...
            }
          ]
 ]
}

any idea how to acheive this using springboot mongotemplate or by using raw mongo知道如何使用 springboot mongotemplate 或使用 raw mongo 来实现这一点

Group both market and field first, then group market.先对市场和领域进行分组,再对市场进行分组。

You should group them twice.您应该将它们分组两次。

And try "Reverse Thinking" of group.并尝试小组的“逆向思维”。

db.collection.aggregate([
  {
    $group: {
      _id: {
        market: "$market",
        field: "$field"
      },
      sumOfAmounts: {
        $sum: "$amount"
      }
    }
  },
  {
    $group: {
      _id: "$_id.market",
      result: {
        $push: {
          field: "$_id.field",
          sumOfAmounts: "$sumOfAmounts"
        }
      }
    }
  },
  {
    $set: {
      market: "$_id"
    }
  }
])

mongoplayground mongoplayground

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM