MongoDB $range

The MongoDB $range operator is a custom operator that generates an array of numbers based on a given start value, end value, and step value. This operator is a useful tool for generating sequences of numbers for use in data manipulation or analysis. It is typically used as a component of the $project operator in an aggregate pipeline, to create a new field in the output documents that contain an array of numbers. It takes a total of three arguments: the starting value, the field name on which the range field will be applied, and the increment number to increment value till it reaches the last point of a field value. This guide is going to explain and demonstrate the use of the “range” operator of MongoDB with the help of some examples.

Example # 01:

Make sure that your MongoDB database is already set up on your machine. If not, try installing it along with the creation of a collection in it. The collection must have records. We set up our MongoDB database by creating a collection named “Dummy” and added some documents to it. It is time to use the range operator on a Dummy collection. Before that, we will be displaying the documents we have in our Dummy collection. The instruction shown below is executed in the MongoDB shell for this purpose. The command is using the “find()” method to search for all documents in a collection called “Dummy” with the empty curly braces “{}”. No specific search criteria are being used, so all records in the “Dummy” collection will be displayed.

The output of the command is an array of documents, each record containing several fields. The fields include a unique ObjectId “_id” of each record, the city field represents the name of a city, the count field represents a numerical, the Desc field represents a string describing the city, and the random field is representing a random numerical value.

test> db.Dummy.find({})

[{_id: ObjectId("63c8a1f94ff07039aa6cdf6b"), city: 'Texas', count: 3, Desc: 'Mid-sized city', random: 81},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6c"), city: 'Los Angeles', count: 3, Desc: 'Mid-sized city', random: 5},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6d"), city: 'Italy', count: 10, Desc: 'Most Beautiful and Crowded', random: 12},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6e"), city: 'Istanbul', count: 3, Desc: 'Mid-sized city', random: 95},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6f"), city: 'Delhi', count: 3, Desc: 'Mid-sized city', random: 22}]

It is time to apply the “range” field on all the records of a MongoDB “Dummy” collection to get the range of numbers. The command for the application of the range operator has been attached beneath. It is using the “aggregate()” method to perform an aggregate operation on a collection called “Dummy”. The “$project” operator is used to reshape the documents in a collection by including or excluding fields and can also create new fields. In this case, the “$project” operator is being used to create a new field called “Rest” which is an array containing a range of numbers from 0 to the value of the “random” field in each document, incrementing by 10. The output of the command shows an array of records, the Rest field represents a new array containing a range of numbers based on the value of the “random” field, and the “city” field with the name of a specific city. The rest point can be guessed from the range provided in the “Rest” array field.

test> db.Dummy.aggregate([ {$project: { city: 1, "Rest": {$range: [0, "$random", 10]}}} ])

[{_id: ObjectId("63c8a1f94ff07039aa6cdf6b"), city: 'Texas', Rest: [0, 10, 20, 30, 40, 50, 60, 70, 80]},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6c"), city: 'Los Angeles', Rest: [0]},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6d"), city: 'Italy', Rest: [0, 10]},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6e"), city: 'Istanbul', Rest: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]},

{_id: ObjectId("63c8a1f94ff07039aa6cdf6f"), city: 'Delhi', Rest: [0, 10, 20]}]

Example # 02:

Let us have a look at another example to use the range field on MongoDB collection. The collection “Test” has been utilized in this example so far. The “find” instruction attached below has been displaying the contents of this collection. The output of the command contains the unique identifier assigned to each document by MongoDB, the field “s” represents the starting point number and the field “e” represents the ending point number.

test> db.Test.find({})

[ { _id: ObjectId("63cb65f0bef5adfc81df628e"), s: 2, e: 8 },

{ _id: ObjectId("63cb65f0bef5adfc81df628f"), s: 1, e: 5 },

{ _id: ObjectId("63cb65f0bef5adfc81df6290"), s: 4, e: 9 } ]

The output shows that the array is created using the $range operator, which takes two arguments: the starting value and the ending value. The starting value is the “s” field and the ending value is the “e” field in the document. The final output of this command is a list of documents, each with an _id, an “s” field, an “e” field, and an “R” field that contains an array of integers. The integers in the “R” field are the range of numbers between the “s” and “e” fields for each document: each with an increment of 1. This is because we did not assign an increment value for the range operator. So, the “range” operator took “1” as the increment value by itself.

test> db.Test.aggregate([ {$project: { s: 1, e:1, "R": {$range: ["$s", "$e"]}}} ] )

[ { _id: ObjectId("63cb65f0bef5adfc81df628e"), s: 2, e: 8, R: [ 2, 3, 4, 5, 6, 7 ] },

{ _id: ObjectId("63cb65f0bef5adfc81df628f"), s: 1, e: 5, R: [ 1, 2, 3, 4 ] },

{ _id: ObjectId("63cb65f0bef5adfc81df6290"), s: 4, e: 9, R: [ 4, 5, 6, 7, 8 ] } ]

Example # 03:

In all the illustrations above, we have only applied the range operator on the fields of collections having integer-type values. We will get an error when we apply the range operator on the string type value. What if we apply it to the decimal-type field values? Let us check that by applying it to a new collection named “Float” in our MongoDB database. The find() function applied to the “Float” collection shows the 5 sets of documents in it. Each document contains its unique identifier, string type field “title”, and the “float-type field “age” containing decimal point values.

test> db.Float.find({})

[{_id: ObjectId("63cb5f26bef5adfc81df6289"), title: 'Nina', age: 45.6},

{_id: ObjectId("63cb5f26bef5adfc81df628a"), title: 'Ana', age: 22.75},

{_id: ObjectId("63cb5f26bef5adfc81df628b"), title: 'Eden', age: 35.9},

{_id: ObjectId("63cb5f26bef5adfc81df628c"), title: 'Rock', age: 82.5},

{_id: ObjectId("63cb5f26bef5adfc81df628d"), title: 'Lia', age: 27}]

Now, we have applied the “range” operator on the Float collection using the aggregate function to get the range of numbers with an increment of 11 for the “age” field. This code, however, generates an error because the $range operator requires that the end value is a 32-bit integer, but the value of the “age” field is a floating point number and it can’t be converted to a 32-bit integer. This shows that we cannot apply the range operator on any other data type except the integer data type in the MongoDB database.

test> db.Float.aggregate([{$project: {title: 1, "Rest": {$range: [0, "$age", 11]}}}])

MongoServerError: PlanExecutor error during aggregation:: caused by:: $range requires an ending value that can be represented as a 32-bit integer, found value: 45.6.


We have briefed the concept of the range operator being utilized in the MongoDB aggregate function. After defining the use of the range operator, we have explained its use with the help of three distinct examples of MongoDB commands in the shell. The first illustration demonstrates the use of the range operator on the integer-type field to get the sequence of numbers with the specific increment number. The second illustrations demonstrate how a range operator can be applied to the start and end field without using the increment number. While the last example shows that the range operator does not work on data types other than integers: floats, and strings.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.