// Sample Data - paste this into the "Documents" section of mongoplayground.net
[
{ "name": "Alice", "money": 1500, "level": 5 },
{ "name": "Bob", "money": 800, "level": 3 },
{ "name": "Charlie", "money": 2000, "level": 7 },
{ "name": "David", "money": 800, "level": 2 },
{ "name": "Eve", "money": 1200, "level": 4 },
{ "name": "Frank", "money": 2000, "level": 6 },
{ "name": "Grace", "money": 500, "level": 1 },
{ "name": "Henry", "money": 1000, "level": 3 },
{ "name": "Ivy", "money": 3000, "level": 8 }
]
// Aggregation Pipeline - paste this into the "Aggregation" section
db.collection.aggregate([
{
$sort: {
money: -1 // Sort in descending order based on the 'money' field
}
},
{
$group: {
_id: {}, // Required even if grouping nothing (creating overall leaderboard)
players: { $push: "$$ROOT" } // Push all documents (players) into an array named 'players'
}
},
{
$unwind: {
path: "$players",
includeArrayIndex: "position" // Add 'position' field representing index in the 'players' array
}
},
{
$addFields: {
position: { $add: [ "$position", 1 ] } // Position starts at 0, so we add 1 to get 1-based indexing.
}
},
{
$replaceRoot: { newRoot: "$players" } // Replace the root document with the 'players' object to return the individual player documents
},
{
$addFields: {
position: "$position" // Promote the position to the document root
}
}
])
Key improvements and explanation:
$sort: { money: -1 }: This is the crucial first step. It sorts the documents by the money field in descending order (highest money first). This ensures the correct ordering for the leaderboard. The -1 indicates descending order.
$group: { _id: {}, players: { $push: "$$ROOT" } }: This step groups all documents into a single document containing a single players array. $$ROOT refers to the entire original document. The _id: {} is essential, and it is an empty object. This is a trick to group all documents together. This is necessary to be able to use $unwind with includeArrayIndex.
$unwind: { path: "$players", includeArrayIndex: "position" }: This unwinds the players array, creating a separate document for each player. The includeArrayIndex: "position" is key. It adds a new field called position to each unwound document, and this field contains the index of that document in the original players array. The index is 0-based.
$addFields: { position: { $add: [ "$position", 1 ] } }: We add 1 to the position field because we want the leaderboard position to start at 1 (instead of 0).
$replaceRoot: { newRoot: "$players" }: After unwinding the player array in the previous stage, the pipeline nests the player document inside the players field of the object. The $replaceRoot stage replaces the entire input document (which is the group object) with the value of the players field. Effectively, this restores each object to its original shape, but now including the position field.
$addFields: { position: "$position" }: After the $replaceRoot stage, the position field could potentially be buried in a sub-document (depending on the structure after the $unwind). This stage ensures that the position field is placed directly at the root level of the document. This is often unnecessary in the current example, but it's a good defensive practice to ensure the position is always in the right place.
This aggregation pipeline first sorts the players by money, then creates a position field based on their sorted order. The final result is a list of player documents, each with its corresponding leaderboard position. This is far more efficient than other methods that might use $reduce or other more complex operators.