Using a collection of test results as an example, you can employ the $rank operator to rank the participants according to their test results. You can then employ this rank in subsequent computations or queries. Finding the top and lowest performers in a dataset, as well as comparing the relative performance of various people or groups, is significant. This guide is helping you to get an idea about the use of the rank operator in MongoDB.
Create MongoDB Collection
Before jumping to the topic, we should be creating an environment to work on. Therefore, we have already installed and configured the MongoDB database on our machine. The command below is being executed in the MongoDB command line interface. The “test” before the “>” symbol indicates that the instruction is being executed in the “test” database. The command being executed is “db.createCollection(“Result”)”. This command creates a new collection within the “test” database called “Result”. The response given is “{ ok: 1 }”. This indicates that the command was successful and the collection “Result” was successfully created. “test” is the name of the database being used.
{ ok: 1 }
Insert Record to Collection
Although we have created a new collection, it is still empty. We need to have at least 2 records in a collection “Result” to apply the rank operator on it. The code below is inserting multiple documents into a collection called “Result” in a MongoDB database. Each record covers two fields, “std” and “score”. Th “std” field represents the name of a student, and the “score” field represents their score on a test. The code is inserting 15 documents in total, with each document representing a different student and their respective score.
Each document is separated by a comma and enclosed in curly braces {}. The scores range from -2 to 99 and the names of the students are Nina, Johny, Eden, Robert, and Lia. Each student has at least 2 scores which is used for 2 different subjects. The insertion of these documents is acknowledged by the database and the code returns a list of unique identifiers (ObjectIds) for each document.
{ acknowledged: true,
insertedIds: {
'0': ObjectId("63cd0bb2f114cb71b42e38e5"),
'1': ObjectId("63cd0bb2f114cb71b42e38e6"),
'2': ObjectId("63cd0bb2f114cb71b42e38e7"),
'3': ObjectId("63cd0bb2f114cb71b42e38e8"),
'4': ObjectId("63cd0bb2f114cb71b42e38e9"),
'5': ObjectId("63cd0c1bf114cb71b42e38ea"),
'6': ObjectId("63cd0c1bf114cb71b42e38eb"),
'7': ObjectId("63cd0c1bf114cb71b42e38ec"),
'8': ObjectId("63cd0c1bf114cb71b42e38ed"),
'9': ObjectId("63cd0c1bf114cb71b42e38ee"),
'10': ObjectId("63cd0cd6f114cb71b42e38ef"),
'11': ObjectId("63cd0cd6f114cb71b42e38f0"),
'12': ObjectId("63cd0cd6f114cb71b42e38f1"),
'13': ObjectId("63cd0cd6f114cb71b42e38f2"),
'14': ObjectId("63cd0cd6f114cb71b42e38f3")
}}
Display MongoDB Records
After inserting the 15 records successfully in the collection “Result”, we will be having a look at all the records once again. For this, the command we have been utilizing has been attached below. This query is using the find() method to retrieve all documents in a collection called “Result”. The find() method is used to return an array of documents in the collection “Result” that match the specified query. In this case, no query is specified. So, all 15 documents in the collection “Result” are returned. The output documents contain three fields: _id, std, and score. The _id field is a unique identifier assigned to each document by MongoDB, the std field contains the name of the student, and the score field contains the test score for each student.
[
{ _id: ObjectId("63cd0bb2f114cb71b42e38e5"), std: 'Nina', score: 56 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e6"), std: 'Johny', score: 77 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e7"), std: 'Eden', score: 32 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e8"), std: 'Robert', score: 96 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e9"), std: 'Lia', score: 12 }
{ _id: ObjectId("63cd0c1bf114cb71b42e38ea"), std: 'Nina', score: 76 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38eb"), std: 'Johny', score: 87 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ec"), std: 'Eden', score: 52 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ed"), std: 'Robert', score: 99 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ee"), std: 'Lia', score: 42 }
{ _id: ObjectId("63cd0cd6f114cb71b42e38ef"), std: 'Nina', score: 32 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f0"), std: 'Johny', score: 67 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f1"), std: 'Eden', score: 42 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f2"), std: 'Robert', score: 89 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f3"), std: 'Lia', score: -2 }
]
Example # 01: Rank in Descending Order
This command is using the aggregate() method to perform an aggregation operation on a collection called “Result” in a MongoDB database. The aggregate() method takes an array as its argument, where each stage transforms the data. In this case, the first stage of the pipeline is using the $setWindowFields operator that is setting the window fields by partitioning the documents by the “std” field, sorting the documents by the “score” field in descending order (-1). The output field is then specified, which creates a new field called “rankScoreForStd” and assigns a rank to each document within its window using the $rank operator.
The final output shows the documents in the “Result” collection with the additional field “rankScoreForStd” added to each document, indicating the rank of the student based on their score. The records are sorted in descending order of score and grouped by student name. In this case, the script is ranking the students based on their scores. The student with the highest score gets a rank of 1, the student with the second highest score gets a rank of 2, and so on.
[
{ _id: ObjectId("63cd0c1bf114cb71b42e38ec"), std: 'Eden', score: 52, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f1"), std: 'Eden', score: 42, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e7"), std: 'Eden', score: 32, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38eb"), std: 'Johny', score: 87, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e6"), std: 'Johny', score: 77, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f0"), std: 'Johny', score: 67, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ee"), std: 'Lia', score: 42, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e9"), std: 'Lia', score: 12, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f3"), std: 'Lia', score: -2, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ea"), std: 'Nina', score: 76, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e5"), std: 'Nina', score: 56, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38ef"), std: 'Nina', score: 32, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ed"), std: 'Robert', score: 99, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e8"), std: 'Robert', score: 96, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f2"), std: 'Robert', score: 89, rankScoreForStd: 3 }
]
Example # 02: Rank in Ascending Order
In the above illustration, we have ranked the documents in descending order of the score field using the score value “-1”. This time, we will perform a rank operation on all the documents in ascending order of the score field. For this, there is a little modification in the same aggregate command, starting from the aggregate() method that is used to process data and return the result in the form of one or more documents.
The $setWindowFields operator is used to add a new field to each document based on the specified window function. The command is setting the window fields by partitioning the documents by the “std” field, sorting the documents by the “score” field in ascending order (1) using the value “1” and then adding a new field called “rankScoreForStd” that assigns a rank to each document based on the score. The output shows an array of all the documents in the “Result” collection, with an additional field “rankScoreForStd” for each document. In this case, each student is assigned a unique rank and the documents are sorted in ascending order of the score.
[
{ _id: ObjectId("63cd0c1bf114cb71b42e38ec"), std: 'Eden', score: 32, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f1"), std: 'Eden', score: 42, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e7"), std: 'Eden', score: 52, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38eb"), std: 'Johny', score: 67, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e6"), std: 'Johny', score: 77, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f0"), std: 'Johny', score: 87, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ee"), std: 'Lia', score: -2, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e9"), std: 'Lia', score: 12, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f3"), std: 'Lia', score: 42, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ea"), std: 'Nina', score: 26, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e5"), std: 'Nina', score: 56, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38ef"), std: 'Nina', score: 76, rankScoreForStd: 3 },
{ _id: ObjectId("63cd0c1bf114cb71b42e38ed"), std: 'Robert', score: 89, rankScoreForStd: 1 },
{ _id: ObjectId("63cd0bb2f114cb71b42e38e8"), std: 'Robert', score: 96, rankScoreForStd: 2 },
{ _id: ObjectId("63cd0cd6f114cb71b42e38f2"), std: 'Robert', score: 99, rankScoreForStd: 3 }
]
Conclusion
After introducing the MongoDB rank operator, we discussed its usage in MongoDB. After that, we created an environment to work on and added MongoDB examples to illustrate the use of the rank operator more precisely. The first example shows the use of the rank operator with the “-1” value to display the documents in descending order. While the second example covers its use with the “1” value to display and rank the documents in ascending order of collection.