$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
-
Performance: Using
$skipcan be resource-intensive on large datasets because MongoDB must scan all the skipped documents. The performance can be improved by using$skipafter a$matchor$sortstage that reduces the number of documents. -
Order of Stages: The placement of
$skipin the pipeline is important. For example, if$skipis used before$sort, the sorting will only apply to the remaining documents after the skip. -
Non-negative Integer: The skip number must be a non-negative integer. Providing a negative number will result in an error.
-
No Guarantee on Order: Unless used with
$sort,$skipdoes not guarantee any particular order of documents.