nikoss nikoss - 5 months ago 60
Node.js Question

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?

Answer

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