具有位置条件的MongoDB分页 [英] MongoDB pagination with location criteria

查看:142
本文介绍了具有位置条件的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值,然后可以使用

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分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆