Spring数据mongodb nearSphere无法使用query.with(pageable)

时间:2014-06-02 22:00:03

标签: mongodb mongodb-java spring-data-mongodb

我正在使用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)不包含任何结果,因为上面的列表将为空。 / p>

如果我注释掉第2行//query.addCriteria(where("location“)。nearSphere(...), 分页工作正常。

顺便说一句,我不能使用mongoTemplate.geoNear(),因为根据this不支持include / exclude

我正在使用spring-data-mongodb-1.5.0.RELEASE和mongodb 2.6.1

知道如何解决这个问题吗?感谢。

1 个答案:

答案 0 :(得分:2)

我自己找到了解决方法。似乎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的错误,但至少它看起来很混乱。