我想订购并限制结果和agregate,$ group和$ push。
假设我有一个在线订单系统。我希望每年按照年份和产品数量获得3个订购最多的产品的清单。
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
返回的对象应该是这样的:
[
{
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
}
]
},
...
]
在猫鼬中我可以按年分组数据:
Orders.model
.aggregate([
{
$group: {
_id: {
'year': '$year',
},
products: {
$push: {
product: '$product',
amount: '$amount'
}
}
}
},
{
$project: {
_id: 0,
year: '$_id.year',
products: '$products'
}
}
])
它会给我所有产品名称和金额,而不是分类。
我不知道如何排序和限制分组数据。 我尝试了$ sort,$ limit,$但没有成功。
答案 0 :(得分:0)
在分组之前对数据进行排序。最后,您可以使用$slice
获取前三个元素:
[
{
$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 ]}
}
}
]