【问题标题】:Unflatten array into a new document and add to the output将数组展开为新文档并添加到输出中
【发布时间】:2017-11-27 13:41:49
【问题描述】:

我的 MongoDB 文档有一个数组属性,其项目类似于原始文档。

我想展开数组属性并将其添加到父级之后:

当前结构:

{
    _id: "1",
    name: "Test1,
    children: [ 
      {         
         _id: "2",
         name: "Test2" 
      }, {
         _id: "3",
         name: "Test3" 
      }]
}

最终结果应该是:

[{
    _id: "1",
    name: "Test1
},
{
    _id: "2",
    name: "Test2
},{
    _id: "3",
    name: "Test3
}]

我尝试过使用 $unwind,但在同一个子属性中保持展开:

{
   path : "$children",
   preserveNullAndEmptyArrays : false // optional
}

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:

    根据示例文档和您预期的结果,您可以尝试:

    db.collection.aggregate([
                 { "$project": { tmp : { 
                              "$concatArrays":[ 
                                             "$children" ,
                                             [ {_id:"$_id", "name": "$name"}]
                                            ]
                                     }
                            }
                 }, 
                 { "$unwind" :"$tmp"}, 
                 { "$replaceRoot" : {newRoot: "$tmp"}}]
    )
    

    $project operatorcombine arrays using $concatArrays operator,将数组children 和根级别_idname 中的所有条目组合到一个名为tmp 的临时字段中。

     {"_id":1,"tmp":[ 
                     {"_id":2,"name":"Test2"},
                     {"_id":3,"name":"Test3"},
                     {"_id":1,"name":"Test1"} ]      
     }
    

    在上述阶段之后,我们将拥有一个包含三个元素的数组。利用$unwind operator,我们可以展开数组元素:

    {"_id":1,"tmp":{"_id":2,"name":"Test2"}},
    {"_id":1,"tmp":{"_id":3,"name":"Test3"}},
    {"_id":1,"tmp":{"_id":1,"name":"Test1"}}
    

    最后,我们使用$replaceRoot 将子文档带到根级别并删除tmp 字段。

    {"_id":2,"name":"Test2"},
    {"_id":3,"name":"Test3"},
    {"_id":1,"name":"Test1"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-06
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2019-11-18
      • 2012-04-12
      • 2021-03-09
      相关资源
      最近更新 更多