Aggregation processes documents through a pipeline of stages:
Documents → Stage 1 → Stage 2 → Stage 3 → Results
local results = collection:Aggregate(pipeline)
{
["$match"] = {
active = true,
level = { ["$gte"] = 10 }
}
}
{
["$group"] = {
_id = "$rank",
count = { ["$sum"] = 1 },
avgLevel = { ["$avg"] = "$level" },
totalCredits = { ["$sum"] = "$credits" }
}
}
{
["$sort"] = { score = -1 } -- -1 = descending
}
{
["$limit"] = 10
}
{
["$project"] = {
_id = 0,
username = 1,
level = 1
}
}
local leaderboard = players:Aggregate({
{ ["$match"] = { active = true } },
{ ["$sort"] = { score = -1 } },
{ ["$limit"] = 10 },
{
["$project"] = {
_id = 0,
username = 1,
score = 1,
level = 1
}
}
})
local stats = players:Aggregate({
{
["$group"] = {
_id = nil,
totalPlayers = { ["$sum"] = 1 },
avgLevel = { ["$avg"] = "$level" },
maxLevel = { ["$max"] = "$level" }
}
}
})
local byRank = players:Aggregate({
{
["$group"] = {
_id = "$rank",
count = { ["$sum"] = 1 },
avgLevel = { ["$avg"] = "$level" }
}
},
{
["$sort"] = { count = -1 }
}
})
| Operator | Description |
|---|---|
$sum | Sum values |
$avg | Average |
$min | Minimum |
$max | Maximum |
$first | First value |
$last | Last value |
$push | Create array |
$match early to filter data$limit to reduce processing$project to return only needed fields