Service » Aggregation

Calculate averages, sums, minimums, maximums, percentiles, and distinct values across your collection using Mondoc's aggregation helpers.

About aggregation

Mondoc provides two ways to run aggregations against your collection: the aggregate() sub-service, which wraps common MongoDB aggregation pipeline operations, and getDistinctValuesForKey(), which is available directly on every service.

All aggregation methods accept an optional $filter array so you can scope results to a subset of documents.

The aggregate() sub-service

Call MyService::aggregate() to obtain the aggregation sub-service for your collection, then chain one of the methods below.

  • getAverage(string $field, array $filter = []): float|int|null
    Returns the average value of $field across all matching documents, or null if no documents match.
  • getSum(string $field, array $filter = []): float|int|null
    Returns the sum of $field across all matching documents.
  • getMin(string $field, array $filter = []): mixed
    Returns the minimum value of $field across all matching documents. Works with both numeric and string fields.
  • getMax(string $field, array $filter = []): mixed
    Returns the maximum value of $field across all matching documents. Works with both numeric and string fields.
  • getPercentile(string $field, float $percentile, int $sortDirection, array $filter = []): float|int|null
    Returns the value at the given percentile position. $percentile is expressed as a fraction between 0 and 1 (e.g. 0.5 for the median, 0.9 for the 90th percentile). $sortDirection controls whether the data is sorted ascending (1) or descending (-1) before the percentile position is resolved.
<?php
// Average age of all users
$avg = MyService::aggregate()->getAverage('age');

// Average age of active users only
$avg = MyService::aggregate()->getAverage('age', ['active' => true]);

// Sum of all order amounts for a specific customer
$total = OrderService::aggregate()->getSum('amount', ['customerId' => $id]);

// Minimum and maximum price in the 'electronics' category
$min = ProductService::aggregate()->getMin('price', ['category' => 'electronics']);
$max = ProductService::aggregate()->getMax('price', ['category' => 'electronics']);

// 90th percentile of scores, sorted ascending
$p90 = ScoreService::aggregate()->getPercentile('score', 0.9, 1);

// Median (50th percentile) of scores
$median = ScoreService::aggregate()->getPercentile('score', 0.5, 1);

Distinct values

getDistinctValuesForKey() is available directly on the service (not through aggregate()) and maps to MongoDB's distinct command.

  • getDistinctValuesForKey(string $key, array $filter = [], array $options = []): array
    Returns an array of unique values for $key across all documents matching $filter. Pass MongoDB command options (e.g. a sort) via $options.
<?php
// All distinct countries in the collection
$countries = UserService::getDistinctValuesForKey('country');

// Distinct countries for active users, sorted alphabetically
$countries = UserService::getDistinctValuesForKey(
    'country',
    ['active' => true],
    ['sort' => ['country' => 1]]
);

// Distinct plan names used by users over the age of 18
$plans = UserService::getDistinctValuesForKey('plan', ['age' => ['$gte' => 18]]);