Below is a “copy‑&‑paste” snippet that you can drop straight into https://mongoplayground.net/ (pick MongoDB 6.0 or newer in the playground).
It does three things:
- Creates a tiny sample collection (
players).
- Uses
$setWindowFields + $denseRank to add a new field called position, where 1 is the richest player.
- Sorts the final result by that new
position field.
/* 1️⃣ Sample data --------------------------------------------------------- */
db.players.drop(); // clean slate (ignore if the coll. is new)
db.players.insertMany([
{ name: "Charlie", money: 1500 },
{ name: "Alice", money: 1200 },
{ name: "Bob", money: 800 },
{ name: "Dave", money: 800 }
]);
/* 2️⃣ + 3️⃣ Add leaderboard position & show result ----------------------- */
db.players.aggregate([
/* Window stage: compute the rank (dense, so ties share the same place) */
{
$setWindowFields: {
sortBy: { money: -1 }, // richest → poorest
output: {
position: { $denseRank: {} } // if you prefer gaps use $rank
}
}
},
/* Optional: present the docs ordered by their new position field */
{ $sort: { position: 1 } }
]);
Expected output:
[
{ "_id": "...", "name": "Charlie", "money": 1500, "position": 1 },
{ "_id": "...", "name": "Alice", "money": 1200, "position": 2 },
{ "_id": "...", "name": "Bob", "money": 800, "position": 3 },
{ "_id": "...", "name": "Dave", "money": 800, "position": 3 }
]
Notes
• $denseRank means players with the same money share a rank and the next rank is +1 (no gaps).
• Swap it for $rank if you want gaps (1, 2, 4…).
• $setWindowFields requires MongoDB 5.0+.