$rank
Assigns rank to each document within a partition based on specified sort order, with gaps in ranking for tied values.
Syntax
{ $rank: {} }
Examples
Ranking stores by sales volume
Rank stores within company partition by total sales in descending order
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "sales.totalSales": -1 }, "output": { "rankBySales": { "$rank": {} } } } }, { $project: { "company": 1, "name": 1, "rankBySales": 1 } }])
Output:
Stores ranked by sales volume with potential gaps for tied values
Rank students by test scores
Assign rankings to students based on examination scores
Query:
db.students.aggregate([{ $setWindowFields: { "partitionBy": "$class", "sortBy": { "testScore": -1 }, "output": { "scoreRank": { "$rank": {} } } } }])
Output:
Students with rankings based on test scores, including gaps for ties