具有位置条件的MongoDB分页

编程入门 行业动态 更新时间:2024-10-24 22:27:42
本文介绍了具有位置条件的MongoDB分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想按字段对数据进行排序.例如

I want get data sorted by field. For example

db.Users.find().limit(200).sort({'rating': -1}).skip(0)

工作正常,我得到了排序后的数据.并可以使用分页.

It's work, I get sorted data. And can use pagination.

但是,如果添加条件.find({'location':{$near : [12,32], $maxDistance: 10}})排序无法正常工作.

But, If add criteria .find({'location':{$near : [12,32], $maxDistance: 10}}) sorting doesn't work correctly.

完整查询:

db.Users.find({'location':{$near : [12,32], $maxDistance: 10}}).limit(200).sort({'rating': -1}).skip(0)

例如

没有条件的位置:

偏移0

rating 100 rating 99 rating 98 rating 97 rating 96

偏移量5

rating 95 rating 94 rating 93 rating 92 rating 91

偏移10

rating 90 rating 89 rating 88 rating 87 rating 86

具有条件位置

偏移0

rating 100 rating 99 rating 98 rating 97 rating 96

偏移量5

rating 90 rating 89 rating 88 rating 87 rating 86

偏移10

rating 95 rating 94 rating 93 rating 92 rating 91

可能是什么问题?我可以在MongoDB中对位置标准使用分页吗?

What could be the problem? Can I use pagination with location criteria in MongoDB?

推荐答案

聚合框架可以使用 $geoNear 流水线阶段.基本上,它将投影"一个距离"字段,然后您可以将其用于组合排序:

The aggregation framework has a way to do this using the $geoNear pipeline stage. Basically it will "project" a "distance" field which you can then use in a combination sort:

db.collection.aggregate([ { "$geoNear": { "near": [12,32], "distanceField": "distance", "maxDistance": 10 }}, { "$sort": { "distance": 1, "rating" -1 } } { "$skip": 0 }, { "$limit": 25 } ])

应该没问题,但是"skip"和"limit"在大跳跃时并不是很有效.如果您不需要页码编号"就可以离开,而只想前进,那么可以尝试另一种方法.

Should be fine, but "skip" and "limit" are not really efficient over large skips. If you can get away without needing "page numbering" and just want to go forwards, then try a different technique.

基本原理是跟踪该页面上找到的最后一个距离值,以及该页面或前几个页面上文档的_id值,然后可以使用 $nin 运算符:

The basic principle is to keep track of the last distance value found for the page and also the _id values of the documents from that page or a few previous, which can then be filtered out using the $nin operator:

db.collection.aggregate([ { "$geoNear": { "near": [12,32], "distanceField": "distance", "maxDistance": 10, "minDistance": lastSeenDistanceValue, "query": { "_id": { "$nin": seenIds }, "rating": { "$lte": lastSeenRatingValue } }, "num": 25 }}, { "$sort": { "distance": 1, "rating": -1 } ])

从本质上讲,这会好得多,但是例如跳转到第25页"并不能帮助您.并非没有更多的精力来解决这个问题.

Essentially that is going to be a lot better, but it won't help you with jumps to "page" 25 for example. Not without a lot more effort in working that out.

更多推荐

具有位置条件的MongoDB分页

本文发布于:2023-11-22 20:52:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   条件   位置   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!