2017-01-09 73 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