$denseRank
Assigns consecutive ranking positions to documents within a partition based on specified sort order, with no gaps in rank values for tied documents.
Syntax
{ $denseRank: {} }
Examples
Retrieve document rank for each store
Calculate dense rank for stores by sales volume within company partition
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "sales.totalSales": -1 }, "output": { "denseRank": { "$denseRank": {} } } } }, { $project: { "company": 1, "sales.totalSales": 1, "denseRank": 1 } }])
Output:
Stores ordered by sales with consecutive dense rank values
Rank products by rating
Dense rank products within categories by customer rating
Query:
db.products.aggregate([{ $setWindowFields: { "partitionBy": "$category", "sortBy": { "rating": -1 }, "output": { "ratingRank": { "$denseRank": {} } } } }])
Output:
Products with dense ranking based on customer ratings within categories