Skip Returned Results跳过返回的结果
On this page本页内容
Overview概述
Use 使用skip
to omit documents from the beginning of the list of returned documents for a read operation. skip
可以省略读取操作返回文档列表开头的文档。You can combine 您可以将skip
with sort to omit the top (for descending order) or bottom (for ascending order) results for a given query. skip
与sort
相结合,以省略给定查询的顶部(对于降序)或底部(对于升序)结果。Since the order of documents returned is not guaranteed in the absence of a sort, using 由于在没有排序的情况下无法保证返回文档的顺序,因此使用skip
without using sort
omits arbitrary documents.skip
而不使用sort
会忽略任意文档。
If the value of 如果skip
exceeds the number of matched documents for a query, that query returns no documents.skip
的值超过查询的匹配文档数,则该查询不返回任何文档。
Sample Documents示例文档
To follow along with the examples in this guide, use the following code snippet to insert documents that describe fruits into the 要遵循本指南中的示例,请使用以下代码片段将描述水果的文档插入myDB.fruits
collection:myDB.fruits
集合:
const myDB = client.db("myDB");
const myColl = myDB.collection("fruits");
await myColl.insertMany([
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
]);
Your query operation may return a reference to a cursor that contains matching documents. 您的查询操作可能会返回对包含匹配文档的游标的引用。To learn how to examine data stored in the cursor, see the Cursor Fundamentals page.要了解如何检查存储在游标中的数据,请参阅游标基础页面。
Example实例
In the following example, we query the collection with a filter that matches all the documents and pass options that specifies 在下面的示例中,我们使用匹配所有文档的筛选器和将sort
and skip
commands as query options. sort
和skip
命令指定为查询选项的传递选项来查询集合。The sort option specifies that fruit documents with higher ratings should be returned before ones with lower ratings. 排序选项指定具有较高评级的水果文档应在具有较低评级的文档之前返回。The skip option specifies that the first 2 documents should be omitted from the result:跳过选项指定应从结果中省略前两个文档:
//define an empty query document定义一个空的查询文档
const query = {};
const options = {
// sort in descending (-1) order by rating
sort : { rating: -1 },
//omit the first two documents省略前两个文档
skip : 2,
}
const cursor = myColl.find(query, options);
for await (const doc of cursor) {
console.dir(doc);
}
Since we specified that the first 由于我们指定应跳过前两个文档,因此第三和第四高评级的文档由上面的代码片段打印:2
documents should be skipped, the third and fourth highest rating documents are printed by the code snippet above:
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 }
The sort
and skip
options can also be specified as methods chained to the find
method. The following two commands are equivalent:sort
和skip
选项也可以指定为连缀到查找方法的方法。以下两个命令是等效的:
myColl.find(query, { sort: { rating: -1}, skip: 2});
myColl.find(query).sort({rating: -1}).skip(2);