Mongo多级聚合组

时间:2019-06-09 19:49:38

标签: mongodb mongodb-query aggregation-framework

汇总后给出以下数据:

let workOrders = [
    {customer: 'A', job: 'Apple', chemical: {name: 'Chem A', quantity: 500}},
    {customer: 'A', job: 'Banana', chemical: {name: 'Chem B', quantity: 400}},
    {customer: 'A', job: 'Banana', chemical: {name: 'Chem C', quantity: 300}},
    {customer: 'B', job: 'Cherry', chemical: {name: 'Chem A', quantity: 200}}
]

所需的输出:

[
  {
    customer: 'A',
    jobs: [
      {
        job: 'Apple',
        chemicals: [
          {name: 'Chem A', quantity: 500}
        ]
      },
      {
        job: 'Banana',
        chemicals: [
          {name: 'Chem B', quantity: 400},
          {name: 'Chem C', quantity: 300}
        ]
      }
    ]
  },
  {
    customer: 'B',
    jobs: [
      {
        job: 'Cherry',
        chemicals: [
          {name: 'Chem A', quantity: 200}
        ]
      }
    ]
  }
]

我了解如何首先按客户分组和分组,但随后我不了解如何在不弄乱初始客户群的情况下制作嵌套化学品阵列。

我尝试了类似的方法,但是它不喜欢内部的$ push。

{ "$group": { "_id": "$customer", "groups": { $push: { "group_data": "$customer", "group_count": {$sum: "$customer"}, "group_child": { $push: { "group_data": "$job", "group_count": {$sum: "$job"}, "group_children": { $push: { "group_data": "$chemical.name", "group_count": {$sum: "$chemical.name"} } } } } } } }

还希望添加每个客户和每个职位的数量总计

2 个答案:

答案 0 :(得分:1)

要制造嵌套式化学品,您仅需要两个$group阶段:

    db.collection.aggregate([
    {
        $group: {
            _id: { customer: "$customer", job: "$job" },
            chemicals: { $push: "$chemical" },
            jobTotal: { $sum: "$chemical.quantity" }
        }
    },
    {
        $group: {
            _id: "$_id.customer",
            jobs: { $push: { job: "$_id.job", jobTotal: "$jobTotal", chemicals: "$chemicals" } },
            customerTotal: { $sum: "$jobTotal" }
        }
    },
    {
        $project: {
            _id: 0,
            customer: "$_id.customer",
            customerTotal: 1,
            jobs: 1
        }
    }
])

Mongo Playground

答案 1 :(得分:0)

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
             _id:{job:'$job'},
             chemicals:{$push:'$chemical'},
             docObj:{$first:'$$CURRENT'}

            }
        },

        // Stage 2
        {
            $group: {
                _id:{customer:'$docObj.customer'},
                jobs:{$push:{job:'$_id.job',chemicals:'$chemicals'}}

            }
        },

        // Stage 3
        {
            $project: {
               customer:'$_id.customer',
               jobs:1,
               _id:0
            }
        },

    ]



);