Advanced Features

Aggregation Pipelines

Process and analyze data with MongoDB aggregation

What is Aggregation?

Aggregation processes documents through a pipeline of stages:

Documents → Stage 1 → Stage 2 → Stage 3 → Results

Basic Usage

local results = collection:Aggregate(pipeline)

Common Stages

$match - Filter

{
    ["$match"] = {
        active = true,
        level = { ["$gte"] = 10 }
    }
}

$group - Group & Calculate

{
    ["$group"] = {
        _id = "$rank",
        count = { ["$sum"] = 1 },
        avgLevel = { ["$avg"] = "$level" },
        totalCredits = { ["$sum"] = "$credits" }
    }
}

$sort - Sort Results

{
    ["$sort"] = { score = -1 }  -- -1 = descending
}

$limit - Limit Results

{
    ["$limit"] = 10
}

$project - Select Fields

{
    ["$project"] = {
        _id = 0,
        username = 1,
        level = 1
    }
}

Real Examples

Leaderboard

local leaderboard = players:Aggregate({
    { ["$match"] = { active = true } },
    { ["$sort"] = { score = -1 } },
    { ["$limit"] = 10 },
    {
        ["$project"] = {
            _id = 0,
            username = 1,
            score = 1,
            level = 1
        }
    }
})

Statistics

local stats = players:Aggregate({
    {
        ["$group"] = {
            _id = nil,
            totalPlayers = { ["$sum"] = 1 },
            avgLevel = { ["$avg"] = "$level" },
            maxLevel = { ["$max"] = "$level" }
        }
    }
})

Group by Category

local byRank = players:Aggregate({
    {
        ["$group"] = {
            _id = "$rank",
            count = { ["$sum"] = 1 },
            avgLevel = { ["$avg"] = "$level" }
        }
    },
    {
        ["$sort"] = { count = -1 }
    }
})

Accumulator Operators

OperatorDescription
$sumSum values
$avgAverage
$minMinimum
$maxMaximum
$firstFirst value
$lastLast value
$pushCreate array

Best Practices

  • Put $match early to filter data
  • Use $limit to reduce processing
  • Use $project to return only needed fields
  • Aggregation is more efficient than Lua processing