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

限制返回结果的数量

在此页面上

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

使用 limit来限制读取操作可以返回的文档数量。 limit用作操作可以返回的最大文档数的上限,但如果存在的文档不足以达到此上限,则操作可能会返回较少数量的文档。如果将limit skip方法一起使用,则首先应用 skip,并且限制仅应用于在 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 },
]);

注意

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

以下示例查询集合以返回长度排名前三的图书。它匹配所有文档,因为查询过滤器为空。然后,它对 length 字段应用降序 sort 以在较短图书之前返回较长图书,并应用 limit 以仅返回前 3 个结果:

// 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 });

您还可以应用 sortlimit,方法是在 find() 方法调用的 options 对象中指定它们。以下两个调用是等效的:

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

options有关find() 方法的 设置的详情,请参阅有关 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 }

您可以通过这种将 skip 和 limit 组合使用的方式为您的集合实现分页,一次仅返回集合中的一小部分数据。

← 跳过返回的结果