简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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