I want to order and limit the results of and agregate, $group and $push.
Let's say that I have a system with online orders. And I want to get a list with 3 most ordered products each year sorted by year and products amount.
year product amount
2016 product A 100
2016 product B 200
2016 product C 300
2016 product D 1000
2016 product E 50
2015 product F 100
2015 product G 800
2015 product A 300
2015 product B 400
2015 product C 100
2014 product A 70
2014 product B 50
2014 product G 500
2014 product C 600
2014 product D 900
The returned object should be something like this:
[
{
year: 2016,
products: [
{
product: 'product D',
amount: 1000
},
{
product: 'product C',
amount: 300
},
{
product: 'product B',
amount: 200
}
]
},
{
year: 2015,
products: [
{
product: 'product G',
amount: 800
},
{
product: 'product B',
amount: 400
},
{
product: 'product A',
amount: 300
}
]
},
...
]
In mongoose I can group data by year:
Orders.model
.aggregate([
{
$group: {
_id: {
'year': '$year',
},
products: {
$push: {
product: '$product',
amount: '$amount'
}
}
}
},
{
$project: {
_id: 0,
year: '$_id.year',
products: '$products'
}
}
])
It will give me all product names and amounts and not sorted.
By I don't know how to sort and limit the grouped data. I tried $sort, $limit, $each without success.
Sort your data before grouping. Then at the end you can use $slice
to get the top three elements:
[
{
$sort: {
year:-1,
amount:-1
}
},
{
$group: {
_id: {
'year': '$year',
},
products: {
$push: {
product: '$product',
amount: '$amount'
}
}
}
},
{
$project: {
_id: 0,
year: '$_id.year',
product: {$slice: [ "$products", 3 ]}
}
}
]
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.