Docs Menu

Skip Returned Results

On this page

  • Overview
  • Sample Documents
  • Example

Use skip to omit documents from the beginning of the list of returned documents for a read operation. You can combine skip with sort to omit the top (for descending order) or bottom (for ascending order) results for a given query. Since the order of documents returned is not guaranteed in the absence of a sort, using skip without using sort omits arbitrary documents.

If the value of skip exceeds the number of matched documents for a query, that query returns no 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 },
]
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. 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 = 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:

{ "_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:

collection.find(query, { sort: { rating: -1}, skip: 2});
collection.find(query).sort({rating: -1}).skip(2);
←  Sort ResultsLimit the Number of Returned Results →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.