$range (Generate Number Sequence)
Last updated: 2026-10-09
$range (Generate Number Sequence)
$range produces a sequence of integers from a start value up to (but excluding) an end value, with an optional step. Typical uses: building date sequences with $dateAdd, generating page numbers for pagination, or fabricating test data at scale. The step defaults to 1 and may be negative for descending sequences; a step of 0 throws an error. The result array holds integers and is often fed into $map to generate fields in bulk.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $range: [ <start>, <end>, <step> ] }
⚙️ Parameters
| start | The starting integer of the sequence, inclusive. |
|---|---|
| end | The ending integer of the sequence, exclusive. |
| step | Optional difference between neighbors, defaults to 1; must not be 0. |
Returns:An array of integers from start up to (excluding) end
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $range: generate the numbers 0 to 4
db.test.aggregate([
{ $project: {
nums: { $range: [0, 5] }
} }
])
Output:
{ '_id': 1, 'nums': [ 0, 1, 2, 3, 4 ] }
📌 Notes
- The end value is excluded; [0, 5] yields 0 through 4
- A step of 0 throws; negative steps count down from start
- Often combined with $map/$dateAdd for date or number sequences
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs the end value included?
ANo — the range is left-closed and right-open, so [0, 5] ends at 4.
QCan I generate a descending sequence?
AYes — use a negative step, e.g. { $range: [5, 0, -1] } yields 5 down to 1.
QCan the step be 0?
ANo, a step of 0 throws an error.