Skip Returned Results跳过返回的结果

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. 您可以将skipsort结合使用,以省略给定查询的顶部(降序)或底部(升序)结果。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的值超过查询的匹配文档数,则该查询不返回任何文档。

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 },
]
Note

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.要了解如何检查游标中存储的数据,请参阅游标基础知识页面

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. 在下面的示例中,我们使用一个匹配所有文档的过滤器查询集合,并使用传入选项将sortskip命令指定为查询选项。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. sortskip选项也可以指定为连缀到find方法的方法。The following two commands are equivalent:以下两个命令是等效的:

collection.find(query, { sort: { rating: -1}, skip: 2});
collection.find(query).sort({rating: -1}).skip(2);