在pymongo中如何将数据filter并且group后取出若干条?
如果我们要在MongoDB查询分组并获取TopN数据
数据为
```
[
{ "name": "刘大", "age": 28, "status": "active" },
{ "name": "陈二", "age": 25, "status": "active" },
{ "name": "张三", "age": 25, "status": "active" },
{ "name": "李四", "age": 25, "status": "active" },
{ "name": "王五", "age": 23, "status": "active" },
{ "name": "赵六", "age": 23, "status": "active" },
{ "name": "孙七", "age": 23, "status": "inactive" },
{ "name": "周八", "age": 23, "status": "active" }
]
```
```
db.user.aggregate([
{
$match: {
status: 'active',
},
},
{
$sort: {
age: 1,
createdAt: 1,
},
},
{
$group: {
_id: '$age'
persons: {
$push: '$$ROOT',
},
},
},
{
$project: {
_id: 0,
age: "$_id",
persons: {
$slice: [
'$persons',
2,
],
},
},
},
]);
```
```
[
{ "name": "王五", "age": 23, "status": "active" },
{ "name": "赵六", "age": 23, "status": "active" },
{ "name": "陈二", "age": 25, "status": "active" },
{ "name": "张三", "age": 25, "status": "active" },
{ "name": "刘大", "age": 28, "status": "active" }
]
```
但是如果我们要使用filter怎么办呢?
我们可以在$project中使用,如下:
![](https://img.kancloud.cn/2b/38/2b38e3780ce3fb3609bc4cb82639b20c_584x250.png)