πŸ“ˆBucket

Documents distribution

Bucket - $bucket

The $bucket operator is used to categorize documents into groups (buckets) based on a specified expression and boundaries. It's used when you need to view the distribution of documents based on a specific criteria.

The sample finds the distribution among Traveler documents based on their age and for each bucket also finds the average age and the total documents. The boundaries (ages) is a fixed array [20, 32, 45, 60, 80] so the result presents the distribution of documents to these boundaries.

Bucket.cs
var travelersCollection = database
    .GetCollection<Traveler>(Constants.TravelersCollection);

var aggregate = travelersCollection.Aggregate();

var bucket = aggregate.Bucket(
    t => t.Age,
    new[] { 20, 32, 45, 60, 80 },
    g => new
    {
        _id = default(int),
        averageAge = g.Average(e => e.Age),
        totalTravelers = g.Count()

    });

var bucketResults = await bucket.ToListAsync();

BucketAuto - $bucketAuto

The $bucketAuto operator works similar to the $bucket except that it automatically determines the boundaries for you. The boundaries are created so that the results are evenly distributed to the specified number of buckets.

The sample distributes the documents based on their age to 4 buckets.

Bucket.cs
var travelersCollection = database
    .GetCollection<Traveler>(Constants.TravelersCollection);

var aggregate = travelersCollection.Aggregate();

// try to create 4 buckets
var autoBucket = aggregate.BucketAuto(t => t.Age, 4);

var autoBucketResults = await autoBucket.ToListAsync();

Last updated