如何在MongoDB中的Collection内创建根元素?

时间:2018-02-04 14:50:40

标签: mongodb aggregation-framework

我导入了这个:

{Crs:{[
       {Cr: {
            "_id" : ObjectId("5a75baada0f20bd4e612d480"),
            "Number" : 400,
            "Page" : 24,
            "DC" : "NE",
        }},
       {Cr: {
            "_id" : ObjectId("5a75baada0f20bd4e612d489"),
            "Number" : 300,
            "Page" : 14,
            "DC" : "100",
        }},
 ]}}

我把数据放在这样的数组中:

{Main: {
    "_id" : ObjectId("main1"),
    "Name" : "MainNAme1",
    {Crs:{[
           {Cr: {
                "_id" : ObjectId("5a75baada0f20bd4e612d480"),
                "Number" : 400,
                "Page" : 24,
                "DC" : "NE",
            }},
           {Cr: {
                "_id" : ObjectId("5a75baada0f20bd4e612d489"),
                "Number" : 300,
                "Page" : 14,
                "DC" : "100",
            }},
     ]}},
}}

我有这个数据,我是importet,我想知道我是如何把它放在我的Main元素中并使用聚合这样建模。

max

1 个答案:

答案 0 :(得分:1)

你可以尝试这种聚合

db.crs.aggregate(
  [
    {$group : {_id : null, crs : {$push : {cr : "$$ROOT"}}}},
    {$addFields : {"Main._id" : "main1", "Main.name" : "MainNAme1", "Main.crs" : "$crs"}},
    {$project : {_id : 0 , crs : 0}}
  ]
)