文档中所有数组大小的MongoDB总和

时间:2019-02-14 08:24:45

标签: mongodb mongodb-query aggregation-framework

在MongoDB上,我有一个这样的集合:-

{
  org: "org",
  departments: [
    {
       name: "abc",
       employees: [
         { name: "number1" },
         { name: "number2" },
         { name: "number3" },
       ]
    },
    {
       name: "mno",
       employees: [
         { name: "number4" },
         { name: "number5" }
       ]
    },
    {
       name: "xyz",
       employees: [
         { name: "number6" },
         { name: "number7" }
       ]
    }
  ]
},{
  org: "xyz"....
}

如何通过使用汇总查找“组织”中的雇员总数? 期待结果 {    org:“ org”,    员工总数:7 }, {   org:“ xyz”,   员工总数:x } ..

2 个答案:

答案 0 :(得分:2)

您可以使用$size来获取内部数组的长度,并使用$reduce来求和这些长度:

db.collection.aggregate([
    {
        $project: {
        total_employees: {
            $reduce: {
                input: "$departments",
                initialValue: 0,
                in: { $add: [ "$$value", { $size: "$$this.employees" } ]  }
            }
        }
        }
    }
])

Mongo playground

答案 1 :(得分:2)

您可以使用$size聚合通过遍历departments数组来找到数组的$map(长度),然后可以$sum一起将所有数组值

db.collection.aggregate([
  { "$project": { 
    "total_employees": {
      "$sum": {
        "$map": { 
          "input": "$departments",
          "in": { "$size": "$$this.employees" }
        }
      }
    }
  }}
])

Output

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "total_employees": 7
  }
]