nikoss
nikoss

Reputation: 3678

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?

Upvotes: 2

Views: 966

Answers (2)

Clement Amarnath
Clement Amarnath

Reputation: 5466

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.

Upvotes: 1

Sede
Sede

Reputation: 61225

To reshape your documents, you need to add a $project stage to your pipeline and use the dot notation to access the sub-documents' fields.

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

Upvotes: 2

Related Questions