Lesson 2: Using MongoDB Aggregation Stages with C#: $match and $group / Learn

Using MongoDB Aggregation Stages with C#: Match and Group

Review the following code, which demonstrates how to use the Match and Group aggregation methods in MongoDB.


Match by Using C# Class

Match filters documents that match the specified conditions and passes them to the next stage of the pipeline. In following code, we request all documents where the Balance field has a value that's less than or equal to 1000. We can view the results by casting the aggregate object to a list.

var matchStage = Builders<Accounts>.Filter.Lte(u => u.Balance, 1000);
var aggregate = accountsCollection.Aggregate()
                          .Match(matchStage);
var results = aggregate.ToList();

foreach (var account in results)
{
    Console.WriteLine(account.Balance);
}


Match by Using BsonDocument

Match filters documents that match the specified conditions to the next stage of the pipeline. When you're working with BsonDocuments, the process is identical, except that we use a builder of type BsonDocument. Also, we can’t use LINQ to define the properties that we want to filter on. Here's an example:

var matchStage = Builders<BsonDocument>.Filter.Lte("balance", 1000);
var aggregate = accountsCollection.Aggregate()
                          .Match(matchStage);
var results = aggregate.ToList();

foreach (var account in results)
{
    Console.WriteLine(account.Balance);
}


Group Stage

The Group stage separates documents into groups according to a group key. The output of this stage is one document for each unique group key. In the following code, we use a LINQ expression and create a new generic object with the fields we want. We keep the same names for the first three properties: AccountId, AccountType, and Balance. We also create a new field called GBP, which is calculated by dividing the current Balance field by 1.3.

var matchStage = Builders<BsonDocument>.Filter.Lte("balance", 1000);
var aggregate = accountCollection.Aggregate()
   .Match(matchStage)
   .Group(
       a => a.AccountType,
       r => new
       {
           accountType = r.Key,
           total = r.Sum(a => 1)
       }
   );

var results = aggregate.ToList();

foreach (var account in results)
{
    Console.WriteLine(account.Balance);
}