【问题标题】:Scalable Express + Mongoose Sort and Limit PaginationScalable Express + Mongoose 排序和限制分页
【发布时间】:2017-05-23 13:52:19
【问题描述】:

我正在努力研究如何有效地对数据进行分页。如果我有一个 URL,例如:example.com/items?page=5,我怎样才能每次都检索到正确的记录(这样同一记录就不会出现在另一个页面上)?我想我必须先对数据库记录进行排序,然后使用 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.
})

【问题讨论】:

  • 是的,排序是必要的,这需要时间,但请记住为要排序的字段编制索引。
  • 太棒了!谢谢你的提示。我将索引我的排序标准:)

标签: javascript node.js mongodb pagination


【解决方案1】:

您可以处理以下查询:

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

在哪里

  1. 条件是 { age: { $gt: 20 } }
  2. 排序会说{名称:1}
  3. 跳过会说 20
  4. 限制是 10

然后执行以下查询以获取记录

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

【讨论】:

  • 感谢您的回答!我只是担心根据https://docs.mongodb.com/manual/reference/method/cursor.skip/skip() 方法是“CPU 密集型。随着更大的集合,cursor.skip() 可能成为 IO 绑定”
  • 如何获取总页数?
猜你喜欢
  • 2020-04-23
  • 2016-09-23
  • 2019-01-31
  • 2017-12-06
  • 2015-12-20
  • 2020-02-29
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
相关资源
最近更新 更多