本文主要是介绍pymongo中如何将数据filter并且group后取出若干条?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在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://blog.csdn.net/ghosind/article/details/109789617
这篇关于pymongo中如何将数据filter并且group后取出若干条?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!