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

查看:27
本文介绍了带有位置条件的 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 }
])

应该没问题,但是跳过"和限制"在大跳过上并不是很有效.如果您可以在不需要页码"的情况下离开并且只想继续前进,那么请尝试不同的技术.

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

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