$rank
New from version 8.0.2.
The $rank window operator in Amazon DocumentDB returns the position of each document within its partition, according to the $setWindowFields stage sortBy order. Documents with the same sortBy value receive the same rank, and the next distinct value skips the intervening positions, leaving gaps (for example, 1, 2, 2, 4). It is specified under the output field of the $setWindowFields stage.
It is a window operator that is used only in the $setWindowFields stage.
Parameters
-
$ranktakes an empty document{}as its value. -
It does not accept a
windowframe. -
It requires exactly one
sortBykey in the$setWindowFieldsstage.
Example (MongoDB Shell)
The following example partitions the documents by game, sorts each partition by score in descending order, and assigns each player a rank.
Create sample documents
db.players.insertMany([ { _id: 1, game: "A", player: "Alice", score: 90 }, { _id: 2, game: "A", player: "Bob", score: 85 }, { _id: 3, game: "A", player: "Carol", score: 85 }, { _id: 4, game: "A", player: "Dave", score: 70 }, { _id: 5, game: "B", player: "Erin", score: 95 }, { _id: 6, game: "B", player: "Frank", score: 80 } ]);
Query example
db.players.aggregate([ { $setWindowFields: { partitionBy: "$game", sortBy: { score: -1 }, output: { rank: { $rank: {} } } } } ]);
Output
[
{ "_id": 1, "game": "A", "player": "Alice", "score": 90, "rank": 1 },
{ "_id": 2, "game": "A", "player": "Bob", "score": 85, "rank": 2 },
{ "_id": 3, "game": "A", "player": "Carol", "score": 85, "rank": 2 },
{ "_id": 4, "game": "A", "player": "Dave", "score": 70, "rank": 4 },
{ "_id": 5, "game": "B", "player": "Erin", "score": 95, "rank": 1 },
{ "_id": 6, "game": "B", "player": "Frank", "score": 80, "rank": 2 }
]
Within each game partition, players are ranked by descending score. Bob and Carol tie at 85 and share rank 2, so the next rank skips to 4 for Dave.
Code examples
To view a code example for using the $rank operator in the $setWindowFields stage, choose the tab for the language that you want to use: