Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何在MongoDB中合并子文档的嵌套数组(数组中的数组)_Arrays_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

Arrays 如何在MongoDB中合并子文档的嵌套数组(数组中的数组)

Arrays 如何在MongoDB中合并子文档的嵌套数组(数组中的数组),arrays,mongodb,mongodb-query,aggregation-framework,Arrays,Mongodb,Mongodb Query,Aggregation Framework,我想在MongodB中组合数组中的数组 比如说,, 测试集合具有以下格式的文档 **{ cmp_id :1 depts : [{"dept_id":1, emps:[1,2,3]}, {"dept_id":2, emps:[4,5,6]}, {"dept_id":2, emps:[7,8,9]} ] }** 我需要以下输出,我怎么能 ***{ cmp_id :1, empids : [1,2,3,4,5,6,7,8,9] }*** 您可以使用下面的聚合 db.collection.aggre

我想在MongodB中组合数组中的数组

比如说,, 测试集合具有以下格式的文档

**{
cmp_id :1
depts : [{"dept_id":1, emps:[1,2,3]}, {"dept_id":2, emps:[4,5,6]}, {"dept_id":2, emps:[7,8,9]} ]
}**
我需要以下输出,我怎么能

***{
cmp_id :1,
empids : [1,2,3,4,5,6,7,8,9]
}***

您可以使用下面的聚合

db.collection.aggregate([
  {
    $project: {
      depts: {
        $reduce: {
          input: "$depts",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this.emps"
            ]
          }
        }
      }
    }
  }
])

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$depts"
            }
        },

        // Stage 2
        {
            $unwind: {
                path: "$depts.emps"
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$cmp_id',
                empids: {
                    $push: '$depts.emps'
                }

            }
        },

    ]



);