首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring数据mongodb nearSphere不使用query.with(可分页)

Spring数据mongodb nearSphere不使用query.with(可分页)
EN

Stack Overflow用户
提问于 2014-06-02 22:00:03
回答 1查看 1.6K关注 0票数 3

我正在使用对MongoDB geo结果进行分页。

下面是相关代码(使用MongoTemplate):

代码语言:javascript
复制
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,它不支持包含/排除

我正在使用SpringDataMongoDB1.5.0 mongodb和MongoDB2.6.1

知道怎么解决这个问题吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-03 02:15:33

我自己找到了解决办法。MongoDB似乎在$nearSphere (也可能是$near)和其他查询之间在“跳过+限制”上的行为不一致。

当你能做的时候

代码语言:javascript
复制
db.doc.find().skip(10).limit(5)

对于“常规”查询,您必须使用

代码语言:javascript
复制
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 mongodb中,使用mongoTemplate,您可以这样做。

代码语言:javascript
复制
int offset = pageable.getOffset();
query.skip(offset);
query.limit(offset + pageable.getPageSize());
...
mongoTemplate.find(query, ...);

而不是

代码语言:javascript
复制
query.with(pageable);
...
mongoTemplate.find(query, ...);

这给了我预期的结果(使用MongoDB 2.6.1 + Spring 1.5.1)。

我不能说这是否是MongoDB的一个bug,但至少它看起来很混乱。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24004015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档