【问题标题】:Is there a way to know if there are more documents available for pagination in MongoDB?有没有办法知道 MongoDB 中是否有更多可用于分页的文档?
【发布时间】:2017-03-10 16:13:29
【问题描述】:

我正在用 MongoDB 编写一个 Node.JS 应用程序。我需要实现的一件事是对象的列表。感谢this answer,我已经使用skip()limit() 函数实现了分页:

myModel.find()
  .skip(offset)
  .limit(limit)
  .exec(function (err, doc) {
     // do something with objects
  })

问题是,我希望我的端点返回元数据,我需要的字段之一是一个布尔值,表示是否有更多可以加载的对象。

实现这一点的最简单方法是再加载一个对象(以确定是否有更多对象要显示)而不向用户显示,类似这样:

 myModel.find()
  .skip(offset)
  .limit(limit + 1)
  .exec(function (err, doc) {
    var moreAvailable; // are there more documents? 
    if (doc.length > limit) {
      moreAvailable = true;
      doc.length = limit; // don't show the last object to the user
    } else {
      moreAvailable = false;
    }


  })

但我很确定应该有更聪明的方法来做到这一点。是吗?

【问题讨论】:

  • 请求一个额外的对象是 IMO 在 MongoDB 中处理分页的最有效方法。在尝试为此目的使用 count 时我遇到了很多问题(性能方面)(这在 SQL 数据库中几乎是标准的),而同一查询的跳过 + 限制非常快。除非您需要确切知道您有多少页,否则这将是一个足够的解决方案。
  • 嗨。我在复制您的解决方案时遇到了一些问题

标签: node.js mongodb pagination


【解决方案1】:

使用db.collection.find(<query>).count()https://docs.mongodb.com/manual/reference/method/cursor.count/

var total = db.collection.find(<query>).count();
var is_more = total > skip + limit;

【讨论】:

  • 尽量避免计数!使用查询时,计数效率极低,即使在匹配索引时也会出现异常。
猜你喜欢
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2019-11-17
相关资源
最近更新 更多