【问题标题】:How could we merge nested arrays of subdocuments(Array within Array) in MongoDB我们如何在 MongoDB 中合并嵌套的子文档数组(数组中的数组)
【发布时间】:2020-04-05 07:12:24
【问题描述】:

我想在 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]
}***

【问题讨论】:

    标签: arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

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

    MongoPlayground

    【讨论】:

      【解决方案2】:
      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'
                      }
      
                  }
              },
      
          ]
      
      
      
      );
      

      【讨论】:

        猜你喜欢
        • 2020-07-01
        • 2021-05-01
        • 2017-03-03
        • 2019-05-10
        • 1970-01-01
        • 2014-03-30
        • 2023-03-05
        • 2018-06-03
        • 2017-06-05
        相关资源
        最近更新 更多