简体   繁体   English

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

[英]Merge a sub document to main document with mongodb aggregation

Here is a sample record of my collection: 这是我收藏的样本记录:

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

}

Here is what I am doing: 这是我在做什么:

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

And its result is similar to: 其结果类似于:

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

However, what I wanna achieve is: 但是,我想要实现的是:

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

Can I do something with $project operation to merge sub document into the main document? 我可以用$project操作来做一些事情来将子文档合并到主文档中吗?

Here is my approach which is some what closer to your expected result. 这是我的方法,它更接近您的预期结果。

My Sample Data 我的样本数据

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

After executing db.collection.aggregate([{$unwind:"$pages"}]) 执行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" } }

then added $group into the pipeline 然后将$ group添加到管道中

db.collectiom.aggregate([{$unwind:"$pages"}, {$group:{_id:"$pages"}}]); 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" } }

Hope it Helps. 希望能帮助到你。

要调整文档的形状,您需要在管道中添加$project阶段,并使用点号访问子文档的字段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM