MongoDB $range Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $range?

$range is a MongoDB aggregation expression that builds an array of integers from a start value (inclusive) to an end value (exclusive), with an optional step. Think of it as a number-sequence generator.

Remember
$range = [start, start+step, …) until end

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

start inclusive · end exclusive
step defaults to 1 · cannot be 0

{ $range: [0, 5] }     → [0, 1, 2, 3, 4]
{ $range: [0, 10, 2] } → [0, 2, 4, 6, 8]
{ $range: [5, 0, -1] } → [5, 4, 3, 2, 1]
UsePrefer
Integer sequence array$range
One doc per number$range + $unwind
Transform each index$range + $map

How to Use $range in MongoDB

Pick start and end (and step if needed), then attach the array to a field.

  1. Choose an expression stage ($addFields or $project).
  2. Pass [start, end] — remember end is exclusive.
  3. Add a non-zero step for every Nth value or counting down.
  4. Optionally $unwind the array to get one document per number.
PieceRequired?Role
startYesFirst integer (inclusive)
endYesStop before this integer
stepNoIncrement (default 1; ≠ 0)

Pseudocode

Pseudocode
start, end, step = evaluate(args)   // step defaults to 1
result = []
i = start

if step > 0:
    while i < end:
        result.push(i)
        i = i + step
else if step < 0:
    while i > end:
        result.push(i)
        i = i + step
else:
    error   // step cannot be 0

emit { ..., field: result }

Cheat Sheet

Keep these facts handy while building number sequences.

TopicDetail
TypeAggregation expression (returns an array)
Syntax{ $range: [start, end, step?] }
BoundsStart in · end out
Default step1
Empty resultNo integers fit → []
DownwardNegative step
Sample[0, 5] → [0, 1, 2, 3, 4]

Live Preview

Pick a start, end, and step to see the array $range would build.

Simulates { $range: [start, end, step?] } (end exclusive).

Result
{ $range: [0, 5] }

start = 0 (inclusive)
end   = 5 (exclusive)
step  = 1

→ [0, 1, 2, 3, 4]

Worked Walkthrough — Seat Numbers

A small room needs seat labels 1 through 5. Because end is exclusive, we call $range with [1, 6].

Calculation
Want seats: 1, 2, 3, 4, 5

$range: [1, 6]
  start = 1  → include
  next  = 2, 3, 4, 5
  end   = 6  → stop (not included)

result → [1, 2, 3, 4, 5]

If you wrote [1, 5] by mistake:
  → [1, 2, 3, 4]   // missing seat 5

MongoDB Examples

We use one room document. First insert it, then build seat numbers with $range, then show a stepped sequence. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one classroom room named A1 that needs five seats. We save it in a collection named rooms.

mongosh
db.rooms.insertOne({
  _id: 1,
  room: "A1",
  seatCount: 5
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in rooms. Run find() to see it:

mongosh
db.rooms.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id
room"A1"Room name
seatCount5How many seats we want
Picture
seatCount = 5
want labels 1 … 5

$range [1, seatCount + 1]
     = [1, 6]
     → [1, 2, 3, 4, 5]

How It Works

  1. Insert once. insertOne adds a single room document.
  2. Store the count. We will turn 5 into seat numbers next.
  3. find() shows the same shape. Ready for Example 2.

Example 2 — Seat Sequence

Goal: add a seats array [1, 2, 3, 4, 5] using $range from 1 to seatCount + 1.

mongosh
db.rooms.aggregate([
  {
    $addFields: {
      seats: {
        $range: [1, { $add: ["$seatCount", 1] }]
      }
    }
  }
]);

How It Works

  1. Read seatCount. The room still has seatCount: 5 from Example 1.
  2. Make end exclusive. $add: ["$seatCount", 1] → end 6.
  3. Build the array. $range: [1, 6] → [1, 2, 3, 4, 5].

Example 3 — Step of 2

Same room idea, but generate even indexes 0, 2, 4, 6, 8 with an explicit step.

mongosh
db.rooms.aggregate([
  {
    $addFields: {
      evenIndexes: { $range: [0, 10, 2] }
    }
  }
]);

How It Works

  1. Start at 0. First value is included.
  2. Jump by 2. The third argument is the step.
  3. Stop before 10. End is exclusive, so 10 is not in the array.

Edge Cases & Pitfalls

Check these before generating large sequences in production.

end

End is exclusive

Want 1…N? Use [1, N + 1]. Writing [1, N] drops N.

step

Step cannot be 0

A zero step is invalid and errors. Use a positive or negative non-zero step.

empty

Empty arrays are normal

If no integers fit (for example [5, 5] or [5, 0] with step 1), the result is [].

size

Huge ranges cost memory

Very large sequences create large arrays. Keep ranges small, or unwind only what you need.

Performance Notes

ApproachCostBest for
Small $rangeCheap array buildIndexes, seat lists
$range + $unwind1 doc → many docsPer-slot processing
Huge end − startLarge memoryAvoid / chunk instead

Building a short sequence is inexpensive. Cost grows with array length and with $unwind, which multiplies documents.

Key Takeaways

  • Role: build an integer sequence array.
  • Bounds: start inclusive, end exclusive.
  • Step: default 1; use negatives to count down.
  • Sample: [1, 6] → seats [1, 2, 3, 4, 5].

One line: $range answers “give me integers from start up to (but not including) end.”

Frequently Asked Questions

$range builds an array of integers from a start value (inclusive) up to an end value (exclusive), with an optional step. For example, { $range: [0, 5] } returns [0, 1, 2, 3, 4].
Use { $range: [ <start>, <end> ] } or { $range: [ <start>, <end>, <step> ] }. Start is inclusive, end is exclusive, and step defaults to 1. Step cannot be 0.
No. End is exclusive. { $range: [0, 5] } stops before 5. To include 5, use end 6.
Yes. Use a negative step when start is greater than end. Example: { $range: [5, 0, -1] } returns [5, 4, 3, 2, 1].
Create the sequence with $addFields or $project, then $unwind the array to get one document per number. Useful for indexes, seat slots, or repeated rows.
You get an empty array []. For example, { $range: [5, 5] } or { $range: [5, 0] } with the default positive step returns [].

Next: $reduce

Accumulate array elements into one final result.

$reduce tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful