在嵌入式文档数组中执行聚合


"employees":[  
      {  
         "empId":100, 
         "Salary":[  
           1000,2000,3000
         ]
   },
   {  
         "empId":101, 
         "Salary":[  
           3000,4000,500
         ]
   }
   ]

在上面的数组中,我需要聚合工资,例如 1000+3000,2000+4000 e.t.c 并将其放在单独的数组中。

我的聚合结果应该是:添加两个雇员的工资薪水[0]+薪水[0](empId:100 + empId:101=1000+3000,2000+4000,3000+500)

"employees":[  
      {  
         "empId":100, 
         "Salary":[  
           1000,2000,3000
         ]
   },
   {  
         "empId":101, 
         "Salary":[  
           3000,4000,500
         ]
   },
    {  
         "empId":111, 
         "Salary":[  
           4000,6000,3500
         ]
   }
   ]
您需要

$unwind所有数组,然后使用聚合框架进行分组

db.dev777.aggregate([{
            $unwind : "$employees"
        }, {
            $unwind : "$employees.Salary"
        }, {
            $group : {
                _id : "$employees.empId",
                salarySum : {
                    $sum : "$employees.Salary"
                }
            }
        }
    ])

输出:

{
    "_id" : 101.0,
    "salarySum" : 7500.0
},{
    "_id" : 100.0,
    "salarySum" : 6000.0
}

编辑

db.dev777.aggregate([{
            // transform array to document
            $unwind : "$employees"
        }, {
            // transform array to document and add array index to preserve position info
            $unwind : {
                path : "$employees.Salary",
                includeArrayIndex : "arrayIndex"
            }
        },
        {
            $group : {
                // now sum all data by array index field 
                _id : "$arrayIndex",
                salarySum : {
                    $sum : "$employees.Salary"
                }
            }
        }, {
            $sort : {
                // sort by array index field
                _id : 1
            }
        }, {
            $group : {
                // recreate document by pushing back values to an array
                _id : null,
                Salary : {
                    $push : "$salarySum"
                }
            }
        }, {
            $project : {
                //remove id field and add empID field  
                _id : 0,
                 empID:  {
                    $literal : NumberInt(111)
                },
                Salary : 1
            }
        }
    ])

相关内容

  • 没有找到相关文章

最新更新