Skip to content

Separate Result Type Example

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

The type of objects returned from aggregate queries can be different than either the source documents or, if specified, the aggregate types. To return a different type, call the Select method while providing a function that creates a new object of the desired type.

CosmosContainer container = containerResponse.Container;

var queryOptions = new AggregateQueryOptions { PartitionKey = "13" };
var query = container.CreateAggregateDocumentQuery<Sale>(queryOptions)
    .Aggregate(
        first => new SaleAggregate
        {
            Count = 1,
            TotalAmount = first.Amount,
            AverageAmount = first.Amount,
        },
        (aggregate, current) => new SaleAggregate
        {
            Count = aggregate.Count + 1,
            TotalAmount = aggregate.TotalAmount + current.Amount,
            AverageAmount = (aggregate.TotalAmount + current.Amount) / (aggregate.Count + 1),
        })
    .Select(aggregate => new SaleSummary
    {
        TotalAmount = aggregate.TotalAmount,
        AverageAmount = aggregate.AverageAmount,
    })
    .AsDocumentQuery();

var results = new List<SaleSummary>();

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

Clone this wiki locally