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.sort
的情况下使用skip
将忽略任意文档。
If the value of 如果skip
exceeds the number of matched documents for a query, that query returns no documents.skip
的值超过查询的匹配文档数,则该查询不返回任何文档。
Sample Documents样本文件¶
Follow the instructions in the examples below to insert data into a collection and perform a sort and skip on the results of a query. 按照以下示例中的说明将数据插入集合,并对查询结果执行排序和跳过。Consider a collection containing documents that describe varieties of fruit:考虑一个包含描述水果种类的文件的集合:
[
{ "_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:skip
选项指定应从结果中省略前两个文档:
// 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 = collection.find(query, options);
await cursor.forEach(console.dir);
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:2
个文档,因此第三个和第四个最高评级的文档由上面的代码段打印:
{ "_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. sort
和skip
选项也可以指定为连缀到find
方法的方法。The following two commands are equivalent:以下两个命令是等效的:
collection.find(query, { sort: { rating: -1}, skip: 2});
collection.find(query).sort({rating: -1}).skip(2);