I have documents which are product groups, like this:
[
{
options: [],
products: [
{
sku: '123',
name: 'Product name 1'
}, {
sku: '476',
name: 'Product name 2'
}
]
}, {
options: [],
products: [
{
sku: '265',
name: 'Product name 3'
}, {
sku: '789',
name: 'Product name 4'
}
]
}
]
What I need to do is an advanced query which includes sorting not only the product groups, but also the product arrays within.
The method I'm trying at the moment is to use aggregate()
with $unwind
and $sort
, then to try to put the group back together (after the $unwind
has broken the products
array out).
Products.aggregate([
{ $unwind: '$products' },
{ $sort: {
'products.sku': -1
} },
{ $group: {
'_id': '$_id',
something: { $push: '$$ROOT' }
} }
]).exec()
It's obviously the $group
that's not right. I'm using '_id': '$_id'
to put the original MongoDB _id
back, but I don't know how to say:
"group by the product group id, and include all original fields"
So really I'm trying to $unwind
and $sort
the products array, then I want to $wind_it_back_up_again
... :-)
How can I achieve this..?
Update: This question is about keeping all fields while grouping.