天天看点

spring data mongodb查询ObjectId

由于项目的数据量比较大,一直用的MySQL扛不住了,近期考虑在项目中使用MongoDB。虽然对MongoDB也是初次接触,也只能硬着头皮上了。由于涉及到分页展示数据的需求,所以必须考虑分页这一块,MongoDB原生提供了skip和limit的方式。

但是官方文档并不推荐,说会扫描全部文档,然后再返回结果。

The cursor.skip() method requires the server to scan from the beginning of the input results set before beginning to return results. As the offset increases, cursor.skip() will become slower.

 于是百度,Google一番搜索以后看到一种通过记录当前页码最一个记录的ID和limit来实现,考虑到MongoDB会自动生成一个"_id",的唯一字段,于是决定就用它来做分页了。于是就有了这样的代码:

criteria.and("_id").gt(lastId);
query.addCriteria(criteria).limit(rows);
mongoTemplate.find(query, Object.class, "collection");
           

可是一直返回一个空列表,又是一阵捣鼓,查到针对ObjectId的查询需要这么写:

criteria.and("_id").gt(new Object(lastId));
           

还是返回空列表,又是一阵挠头。困扰好久终于在stackoverflow上找到答案,说是针对_id做gt lt判断的时候需要给_id加上排序,要不说这网站强大呢,不是没有道理,这里不得不说一下,国内那博客、问答的网站太多都是直接copy别人的答案,多半的答案完全一样。

Query nextStoryQuery = new Query(); //1
previousStoryQuery.addCriteria(Criteria.where("_id").lt(objID)).limit(1); //2
previousStoryQuery.with(new Sort(Sort.Direction.DESC, "_id")); //3
           

stackoverflow链接:https://stackoverflow.com/questions/30873713/mongotemplate-query-objectid-according-to-greater-than-gt-or-less-than-lt