使用mongodb聚合将子文档合并到主文档

时间:2016-06-30 13:31:23

标签: node.js mongodb mongodb-query aggregation-framework

以下是我的收藏的样本记录:

{
    _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操作将子文档合并到主文档中吗?

2 个答案:

答案 0 :(得分: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([{$ unwind:“$ pages”}]后)

"_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" } }

然后将$ group添加到管道中

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" } }

希望它有所帮助。

答案 1 :(得分:1)

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

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