我正在使用 spring-data-mongodb 对 MongoDB 地理结果进行分页。
这是相关代码(使用 MongoTemplate):
Query query = new Query();
query.addCriteria(where("location").nearSphere(new Point(longitude, latitude)).maxDistance(0.012));
query.with(pageable);
//On any page other than the first page
//the following list is always empty (although the total number of records is much bigger than the page size)
List<MyObject> myObjects = mongoTemplate.find(query, MyObject.class);
第一页(即第 0 页,大小:5)总是正确显示,所有其他页面(即第 1 页,大小:5)不包含任何结果,因为上面的列表是空的。
如果我注释掉第 2 行//query.addCriteria(where("location").nearSphere(...), 分页工作正常。
顺便说一句,我不能使用 mongoTemplate.geoNear() 因为它不支持根据 this 包含/排除
我正在使用 spring-data-mongodb-1.5.0.RELEASE 和 mongodb 2.6.1
知道如何解决这个问题吗?谢谢。
最佳答案
我自己找到了解决方法。似乎 MongoDB 在 $nearSphere(也可能是 $near)和其他查询之间的“skip + limit”行为不一致。
虽然你可以做
db.doc.find().skip(10).limit(5)
对于“常规”查询,您必须使用
db.doc.find({
'location': {
$nearSphere: ...,
$maxDistance: ...
}
}).skip(10).limit(15) //note the number for limit has to be 15, which
//is 'offset + pageSize' <==> '10 + 5'
$nearSphere 查询。
所以在 spring-data-mongodb 中,使用 mongoTemplate,你可以做到这一点
int offset = pageable.getOffset();
query.skip(offset);
query.limit(offset + pageable.getPageSize());
...
mongoTemplate.find(query, ...);
代替
query.with(pageable);
...
mongoTemplate.find(query, ...);
这给了我预期的结果(使用 MongoDB 2.6.1 + Spring Data MongoDB 1.5.1)。
我不能说这是否是 MongoDB 的错误,但至少看起来很困惑。
关于mongodb - Spring data mongodb nearSphere 不使用 query.with(pageable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24004015/