Introduction to MongoDB $range Operator
$range
is an operator in MongoDB’s aggregation pipeline used to generate a sequence of numbers. It can take three parameters: the starting value of the sequence, the ending value, and the step size. With these parameters, $range
can generate a sequence of numbers.
Syntax
The syntax of the $range
operator is as follows:
{ $range: [ <start>, <end>, <step> ] }
Here, <start>
is the starting value of the sequence, <end>
is the ending value, and <step>
is the step size. All three parameters are optional; if not specified, $range
will generate an empty array.
Use cases
The $range
operator is typically used to generate sequences of numbers and can be combined with other aggregation operators to perform more complex operations, such as $map
, $zip
, and more. It can be used to generate arrays of sequences, dates, and more. In the aggregation pipeline, $range
can generate a sequence of numbers within a specified range and perform aggregation operations on that sequence.
Examples
Example 1
The following aggregation pipeline uses the $range
operator to generate an array of a sequence of numbers:
db.numbers.aggregate([
{
$project: {
sequence: {
$range: [0, 10, 2]
}
}
}
])
Running the above aggregation will result in the following output:
{
"sequence": [0, 2, 4, 6, 8, 10]
}
Example 2
The following aggregation pipeline uses the $range
and $map
operators to generate an array of dates:
db.orders.aggregate([
{
$project: {
_id: 0,
dates: {
$map: {
input: {
$range: [
new Date("2022-01-01"),
new Date("2022-01-05"),
24 * 60 * 60 * 1000
]
},
as: "date",
in: {
$dateToString: {
date: "$$date",
format: "%Y-%m-%d"
}
}
}
}
}
}
])
Running the above aggregation will result in the following output:
{
"dates": [
"2022-01-01",
"2022-01-02",
"2022-01-03",
"2022-01-04",
"2022-01-05"
]
}
Conclusion
$range
is a useful operator in MongoDB’s aggregation pipeline that can be used to generate sequences of numbers, dates, and more. It can be combined with other aggregation operators to perform more complex operations and is very flexible in its use within the aggregation pipeline.