2016-06-30 220 views
0

下面是我收集的样本记录:合并子文档主文档与MongoDB的聚集

{ 
    _id:someId, 
    pages:[ 
    {id:id,field:value}, 
    {id:otherId,field:otherValue} 
    ] 

} 

下面是我在做什么:

collection.aggregate([ 
    {$unwind:"$pages"} 
]) 

而其结果是类似于:

{ 
    _id:id, 
    pages:{id:id,field:value} 
}, 
{ 
    _id:id, 
    pages:{id:otherId,field:otherValue} 
} 

不过,我想实现的是:

{ 
    _id:id, 
    id:id, 
    field:value 
}, 
{ 
    _id:id, 
    id:otherId, 
    field:otherValue 
} 

我可以使用$project操作将子文档合并到主文档中吗?

+0

您列为所需输出的结果格式不正确。我不知道如何实现它。 – Tiramisu

+1

@Tiramisu我更新了格式 – nikoss

+1

在'$ unwind'后添加'{“$ project”:{“id”:“$ pages.id”,“field”:“$ pages.field”}}''阵列。 – styvane

回答

1

要重塑您的文档,您需要在管道中添加$project阶段,并使用dot notation访问子文档的字段。

{ "$project": { "id": "$pages.id", "field": "$pages.field" } } 
1

这是我的方法,它是一些更接近您的预期结果。

我的样本数据

"_id" : 1, 
    "pages" : [ 
      { 
        "_id" : "a", 
        "comment" : "Have a Nice Day" 
      }, 
      { 
        "_id" : "b", 
        "comment" : "Everyday is Beautiful" 
      }, 
      { 
        "_id" : "c", 
        "comment" : "All is Well" 
      }, 
      { 
        "_id" : "d", 
        "comment" : "Nature is wonderful" 
      }, 
      { 
        "_id" : "e", 
        "comment" : "Enjoy the moment" 
      } 
    ] 

执行db.collection.aggregate后([{$开卷: “$页”}])

"_id" : 1, "pages" : { "_id" : "a", "comment" : "Have a Nice Day" } } 
"_id" : 1, "pages" : { "_id" : "b", "comment" : "Everyday is Beautiful" } } 
"_id" : 1, "pages" : { "_id" : "c", "comment" : "All is Well" } } 
"_id" : 1, "pages" : { "_id" : "d", "comment" : "Nature is wonderful" } } 
"_id" : 1, "pages" : { "_id" : "e", "comment" : "Enjoy the moment" } } 

加入$组到管道

db.collectiom.aggregate([{$ unwind:“$ pages”},{$ group:{_ id:“$ pages”}}]);

"_id" : { "_id" : "e", "comment" : "Enjoy the moment" } } 
"_id" : { "_id" : "d", "comment" : "Nature is wonderful" } } 
"_id" : { "_id" : "c", "comment" : "All is Well" } } 
"_id" : { "_id" : "b", "comment" : "Everyday is Beautiful" } } 
"_id" : { "_id" : "a", "comment" : "Have a Nice Day" } } 

希望它有助于。

+0

以及这不正是我所寻求的仍然是不合并到主要我猜他们没有办法做到这一点 – nikoss

相关问题