文档菜单
文档首页
/ / /
Node.js 驱动程序
/ / /

限制返回结果的数量

在本页面上

  • 概述
  • 示例文档
  • 限制
  • 跳过

使用limit 用于限制从读取操作中返回的文档数量。 limit 作为操作返回的最大文档数量的上限,但如果文档数量不足以达到上限,操作可以返回更少的文档。如果与 limit 一起使用skip 方法,则跳过操作首先应用,而限制只应用于跳过后的剩余文档。

要遵循本指南中的示例,请使用以下代码片段将描述书籍的文档插入到 myDB.books 集合中

const myDB = client.db("myDB");
const myColl = myDB.collection("books");
await myColl.insertMany([
{ "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 },
{ "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 },
{ "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 },
{ "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 },
{ "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 },
{ "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 },
]);

注意

您的查询操作可能会返回一个包含匹配文档的游标引用。要了解如何检查游标中存储的数据,请参阅 游标基础页面。

以下示例查询集合以返回最长的三本书。由于查询过滤器为空,它匹配所有文档。然后,它对长度字段应用降序排序,以便在较短的书籍之前返回较长的书籍,并应用限制以只返回前三个结果。

// define an empty query document
const query = {};
// sort in descending (-1) order by length
const sort = { length: -1 };
const limit = 3;
const cursor = myColl.find(query).sort(sort).limit(limit);
for await (const doc of cursor) {
console.dir;
}

上述代码示例输出以下三个文档,按长度排序。

{ "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
{ "_id": 6, "title": "A Dance With Dragons", "author": "Martin", "length": 1104 }
{ "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }

注意

调用 limitsort 的顺序无关紧要,因为驱动程序会重新排序调用,先应用排序,然后应用限制。以下两个调用是等效的。

myColl.find(query).sort({ length: -1 }).limit(3);
myColl.find(query).limit(3).sort({ length: -1 });

您还可以通过在调用 find() 方法时指定选项对象来应用 sortlimit。以下两个调用是等效的。

myColl.find(query).sort({ length: -1 }).limit(3);
myColl.find(query, { sort: { length: -1 }, limit: 3 });

有关 find() 方法的 options 设置的更多信息,请参阅find() 的 API 文档.

要查看结果中的下一本书,请附加 skip() 方法,传递要跳过的文档数,如下所示

// define an empty query document
const query = {};
// sort in descending (-1) order by length
const sort = { length: -1 };
const limit = 3;
const skip = 3;
const cursor = myColl.find(query).sort(sort).limit(limit).skip(skip);
for await (const doc of cursor) {
console.dir;
}

此操作返回描述第四到第六本书的文档,按最长到最短的长度顺序排列。

{ "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 }
{ "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
{ "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }

您可以通过这种方式组合跳过和限制来实现集合的分页,一次只返回集合的小“切片”。

返回

跳过返回结果