天天看點

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