Lesson 3: Using MongoDB Aggregation Stages with C#: $sort and $project / Learn

Using MongoDB Aggregation Stages with C#: Sort and Project

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

Sort Stage

A Sort stage sorts all input documents and passes them to the next pipeline stage in the sorted order. This can be a numeric value, strings arranged in alphabetical order, dates, or timestamps. You can define the sort as a LINQ statement within the .SortBy() or .SortByDescending() methods. For example:

var matchBalanceStage = Builders<Accounts>.Filter.Lt(user => user.Balance, 1500);

var aggregate = accountsCollection.Aggregate()                        
                    .Match(matchBalanceStage)
                    .SortByDescending(u => u.Balance):

var results = aggregate.ToList();

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


Sort by Using BsonDocument

A Sort stage sorts all input documents and passes them to the next pipeline stage in the sorted order. This can be a numeric value, strings arranged in alphabetical order, dates, or timestamps. For example:

var matchBalanceStage = Builders<BsonDocument>.Filter.Lt("balance", 1500);
var sort = Builders<BsonDocument>.Sort.Descending("balance");

var aggregate = accountsCollection.Aggregate()
                        .Match(matchBalanceStage)
                        .Sort(sort);
var results = aggregate.ToList();

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


Project Stage

To create a projection, we use the ProjectionDefinitionBuilder. We use the Expression method to define the output of the Project stage.

In the following code, we use a LINQ expression to 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 create a new field called GBP, which is calculated by dividing the current Balance field by 1.3.

var matchBalanceStage = Builders<Accounts>.Filter.Lt(user => user.Balance, 1500);
var projectStage = Builders<Accounts>.Projection.Expression(u =>
    new
    {
        AccountId = u.AccountId,
        AccountType = u.AccountType,
        Balance = u.Balance,
        GBP = u.Balance / 1.30M
    });

var aggregate = accountsCollection.Aggregate()
                        .Match(matchBalanceStage)
                        .SortByDescending(u => u.Balance)
                        .Project(projectStage);

var results = aggregate.ToList();

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