$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $range: [ <start>, <end>, <step> ] }

⚙️ Parameters

startThe starting integer of the sequence, inclusive.
endThe ending integer of the sequence, exclusive.
stepOptional 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏