How to Use $skip in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$skip stage to skip a specified number of documents in the pipeline result. Place $skip after stages like $match or $sort to control which documents appear next, commonly for pagination.Syntax
The $skip stage takes a single numeric argument that specifies how many documents to skip in the aggregation pipeline.
- Number: The count of documents to skip.
- Must be a non-negative integer.
- Used inside an aggregation pipeline array.
json
[
{ "$skip": <number_of_documents_to_skip> }
]Example
This example shows how to skip the first 3 documents after sorting a collection by age in ascending order.
mongodb
db.users.aggregate([
{ "$sort": { "age": 1 } },
{ "$skip": 3 }
])Output
[
{ "_id": 4, "name": "Alice", "age": 30 },
{ "_id": 5, "name": "Bob", "age": 32 },
{ "_id": 6, "name": "Carol", "age": 35 }
]
Common Pitfalls
- Using
$skipwithout a$sortstage can lead to unpredictable results because document order is not guaranteed. - Skipping too many documents may return an empty result set.
- Negative numbers for
$skipare invalid and cause errors.
mongodb
/* Wrong: Skipping without sorting may give inconsistent results */ db.users.aggregate([ { "$skip": 5 } ]) /* Right: Always combine with $sort for predictable output */ db.users.aggregate([ { "$sort": { "age": 1 } }, { "$skip": 5 } ])
Quick Reference
| Stage | Description | Example |
|---|---|---|
| $skip | Skips a specified number of documents | { "$skip": 10 } |
| $sort | Sorts documents before skipping | { "$sort": { "field": 1 } } |
| Usage | Use $skip after $sort for pagination | [{ "$sort": { "age": 1 } }, { "$skip": 5 }] |
Key Takeaways
Use $skip in aggregation to skip a set number of documents in the pipeline.
Always combine $skip with $sort to ensure consistent and predictable results.
The argument to $skip must be a non-negative integer.
Skipping too many documents can result in empty output.
Use $skip for pagination by skipping documents already shown.