// Sample Data (Insert into your MongoDB collection)
db.players.insertMany([
{ name: "Alice", money: 1000 },
{ name: "Bob", money: 1500 },
{ name: "Charlie", money: 800 },
{ name: "David", money: 2000 },
{ name: "Eve", money: 1200 }
]);
// Aggregation Pipeline
db.players.aggregate([
{
$sort: {
money: -1 // Sort in descending order based on the 'money' field
}
},
{
$group: {
_id: null, // Group all documents into a single group
players: { $push: "$$ROOT" } // Push each document into an array called 'players'
}
},
{
$unwind: {
path: "$players", // Unwind the 'players' array to process each document individually
includeArrayIndex: "position" // Add an index to each document called 'position'
}
},
{
$project: {
_id: 0, // Exclude the '_id' field from the output
name: "$players.name", // Project the 'name' field from the original document
money: "$players.money", // Project the 'money' field from the original document
position: { $add: ["$position", 1] } // Add 1 to the 'position' to start it from 1 instead of 0
}
},
{
$sort: {
position: 1 // Sort by position
}
}
]);
Explanation:
-
db.players.insertMany(...): This part is the sample data. Paste this into the "Insert" tab in mongoplayground.net and click "Run". It creates a collection named "players" and inserts sample player data with name and money fields.
-
$sort: { money: -1 }: This stage sorts the documents in descending order based on the money field. Players with the most money will come first. This is crucial for determining leaderboard position.
-
$group: { _id: null, players: { $push: "$$ROOT" } }:
$group is used to group documents together. _id: null means we're grouping all documents into a single group.
players: { $push: "$$ROOT" } creates an array called players. $$ROOT represents the entire document in the current stage, and $push adds each sorted document to the players array. The output will be a single document containing the "players" array.
-
$unwind: { path: "$players", includeArrayIndex: "position" }:
$unwind "deconstructs" the players array. For each element (player) in the array, it creates a separate document.
includeArrayIndex: "position" is the key to generating the position. It adds a field called position to each unwound document. This field will contain the index of that player in the original players array. Importantly, the index starts at 0.
-
$project: { ... }:
$project is used to reshape the documents and select/rename fields.
_id: 0: Excludes the _id field from the final output. (Optional, but cleaner).
name: "$players.name", money: "$players.money": These rename the fields to name and money respectively.
position: { $add: ["$position", 1] }: This is where we adjust the position. Because the $unwind index started at 0, we add 1 to it to get the correct leaderboard position (starting at 1).
-
$sort: {position: 1}: This stage sorts the output results by the 'position' field in ascending order (from 1 upwards). Although the results should already be sorted, this is included to ensure the result is always correctly sorted in the desired order, should prior stages unexpectedly shuffle documents.
How to use in mongoplayground.net:
- Go to https://mongoplayground.net/
- Select MongoDB version 4.4 or higher (the
$add within $project requires at least 4.4).
- In the "Insert" tab, paste the
db.players.insertMany(...) code and click "Run". This will create the sample data.
- In the "Aggregate" tab, paste the aggregation pipeline code (the
db.players.aggregate(...) part) and click "Run".
- The "Results" tab will show the players, each with their name, money, and calculated
position. The player with the most money will have position: 1, the second most position: 2, and so on.