Skip to content

Separate Aggregate Type Example

Chris Dahlberg edited this page Mar 19, 2019 · 1 revision

A type that is not the same as the type of source documents can be used for aggregates. To use a different type, the overload of the Aggregate method that accepts a function to create the initial aggregate object must be used.

CosmosContainer container = containerResponse.Container;

var queryOptions = new AggregateQueryOptions { PartitionKey = "13" };
var query = container.CreateAggregateDocumentQuery<Sale>(queryOptions)
    .Aggregate(
        // Create the initial aggregate from the first source document
        first => new SaleAggregate
        {
            Count = 1,
            TotalAmount = first.Amount,
            AverageAmount = first.Amount,
        },
        // Create a subsequent aggregate from the existing aggregate and the current source document
        (aggregate, current) => new SaleAggregate
        {
            Count = aggregate.Count + 1,
            TotalAmount = aggregate.TotalAmount + current.Amount,
            AverageAmount = (aggregate.TotalAmount + current.Amount) / (aggregate.Count + 1),
        })
    .AsDocumentQuery();

var results = new List<SaleAggregate>();

while (query.HasMoreResults)
{
    var resultsPage = await query.ExecuteNextAsync(cancellationToken).ConfigureAwait(false);
    results.AddRange(resultsPage);
}
Clone this wiki locally