Skip to main content

$skip

The $skip stage in MongoDB's aggregation pipeline is used to skip over a specified number of documents from the pipeline and pass the remaining documents to the next stage. This operation is often used in conjunction with $limit for pagination purposes. It can also be useful for skipping records that you don't want to include in the final output for other reasons.

Basic Syntax

The basic syntax of the $skip stage is as follows:

db.collection.aggregate([
{
$skip: <number>
}
]);
  • <number>: The number of documents to skip. Must be a non-negative integer.

Examples

Simple Skip

To skip the first 5 documents:

db.orders.aggregate([
{
$skip: 5
}
]);

Skip and Limit for Pagination

To implement pagination by skipping the first 20 documents and then limiting the output to 10:

db.orders.aggregate([
{
$skip: 20
},
{
$limit: 10
}
]);

Skip After Sorting

To sort documents by the amount field in ascending order and then skip the first 3:

db.orders.aggregate([
{
$sort: { amount: 1 }
},
{
$skip: 3
}
]);

Considerations

  1. Performance: Using $skip can be resource-intensive on large datasets because MongoDB must scan all the skipped documents. The performance can be improved by using $skip after a $match or $sort stage that reduces the number of documents.

  2. Order of Stages: The placement of $skip in the pipeline is important. For example, if $skip is used before $sort, the sorting will only apply to the remaining documents after the skip.

  3. Non-negative Integer: The skip number must be a non-negative integer. Providing a negative number will result in an error.

  4. No Guarantee on Order: Unless used with $sort, $skip does not guarantee any particular order of documents.