2017-01-09 29 views
0

我正在努力解決如何有效地分頁我的數據。如果我有一個網址,例如:example.com/items?page=5,我怎樣才能每次檢索正確的記錄(這樣相同的記錄就不會顯示在另一頁上)?我想我必須首先對數據庫記錄進行排序,然後使用貓鼬進行範圍查詢,例如下面的查詢。Scalable Express + Mongoose排序和限制分頁

當記錄數量快速增長時,這種做法如何?我擔心分類過程將花費太長時間並且成爲瓶頸。有什麼建議?

Submission.find({ 
    /* First Case: Hour */ 
    created: { $lt: new Date(), $gt: new Date(year+','+month+','+day+','+hour+','+min+','+sec) } // Get results from start of current hour to current time. 
    /* Second Case: Day */ 
    created: { $lt: new Date(), $gt: new Date(year+','+month+','+day) } // Get results from start of current day to current time. 
    /* Third Case: Month */ 
    created: { $lt: new Date(), $gt: new Date(year+','+month) } // Get results from start of current month to current time. 
    /* Fourth Case: Year */ 
    created: { $lt: new Date(), $gt: new Date(year) } // Get results from start of current year to current time. 
}) 
+0

呀排序是必要的,這需要時間,但記得指數要排序的字段。 –

+0

太棒了!感謝您的提示。我會索引我的排序標準:) – Clement

回答

1

您可以在下面的查詢工作:

var query = Model.find(conditions).sort(sort).skip(skip).limit(limit); 

其中

  1. 條件會說{年齡:{$ GT:20}}
  2. 排序會說{名稱:1}
  3. 跳躍會說20
  4. 李麻省理工學院將說10

然後執行以下查詢來獲取記錄

return query 
     .exec() 
     .then(function (cursor) { ...... }); 
+1

感謝您的回答!我只是擔心根據'https:// docs.mongodb.com/ manual/reference/method/cursor.skip /','skip()'方法是「CPU密集型的。對於較大的集合,cursor.skip ()可能會成爲IO界限「 – Clement