mongodb 实现分组分页

本文介绍了如何使用MongoDB的Aggregation框架实现按字段分组和分页查询。通过示例展示了$match、$group、$sort和$limit的操作顺序对结果的影响,并强调了在大数据分页时避免使用skip以优化查询性能。同时,讨论了MongoDB的mapReduce功能及其优缺点,并提供了官方文档链接以供进一步学习。

网上找了很多贴,都没有明确给出方案,自己看了Spring mongo 支持文档和 mongo官方doc之后 得出可以用Aggregation 来轻松实现按字段分组后再分页:下面贴出具体代码

1.mongo shell :

db.getCollection('brief_report').aggregate([

{

"$match" : {

"from_user_id" : 438 ,

"enterprise_id" : 1 ,

"report_type_code" : "350020" ,

"is_deleted" : false

}

} ,

{

"$group" : {

"_id" : "$deadline" ,

"count" : { "$sum" : 1} ,

"objectId" : { "$push" : "$_id"} ,

"statusCodes" : { "$push" : "$status_code"}

}

} ,

{

"$sort" : { "_id" : -1}

} ,

{

"$limit" : 10

}

]);

2.java代码:

3.实验的过程中踩了一个坑,就是鬼使神差的把sort放到最后

实现 MongoDB分组分页功能,可以使用 MongoDB 的聚合(Aggregation)框架来完成。 首先需要使用 $group 操作符对数据进行分组,然后使用 $skip 和 $limit 操作符进行分页操作。 例如,假设有一个名为 orders 的集合,其中包含以下数据: ``` { "_id": ObjectId("60e7c6c8a7e3e66b84a8e9a8"), "customer": "Alice", "product": "A", "quantity": 2, "price": 10 }, { "_id": ObjectId("60e7c6c8a7e3e66b84a8e9a9"), "customer": "Bob", "product": "B", "quantity": 1, "price": 20 }, { "_id": ObjectId("60e7c6c8a7e3e66b84a8e9aa"), "customer": "Alice", "product": "C", "quantity": 3, "price": 15 }, { "_id": ObjectId("60e7c6c8a7e3e66b84a8e9ab"), "customer": "Charlie", "product": "A", "quantity": 1, "price": 10 }, { "_id": ObjectId("60e7c6c8a7e3e66b84a8e9ac"), "customer": "Charlie", "product": "B", "quantity": 2, "price": 20 } ``` 下面是对数据进行分组分页的代码示例: ``` db.orders.aggregate([ { $group: { _id: "$customer", total: { $sum: { $multiply: ["$quantity", "$price"] } } } }, { $sort: { total: -1 } }, { $skip: 0 }, { $limit: 2 } ]) ``` 这个聚合操作将会按照顾客进行分组,并计算每个顾客的订单总金额(quantity * price)。之后按照订单总金额进行降序排序,并跳过前 0 个结果,最后限制结果数量为 2 个。 结果如下: ``` { "_id" : "Alice", "total" : 50 } { "_id" : "Charlie", "total" : 50 } ``` 这个结果表示 Alice 和 Charlie 的订单总金额都是 50 元。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值