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

Video Transcript (English)

Hello! In this video, you will learn how to build an aggregation pipeline that’s composed of the $match, $project, and $sort stages. We’ll use the Aggregates builder class to define these stages.

Let’s start with a brief overview of the $project and $sort stages.

The $sort stage sorts all input documents and returns them in the pipeline. To $sort in ascending order, we use the value of 1, and for descending order we use the value of -1.

The $project stage determines the output document shape. It allows us to specify the existing or new fields that will be returned by the aggregation. This stage performs a projection similar to the one applied in find operations. It should usually be the last stage because it specifies the exact fields in the output.

Now that we’ve covered the stages we’re going to use, let’s build an aggregation pipeline with those stages. The pipeline will find all checking accounts with a balance greater than 1500 and sorts the results in descending order. The query should only return the balance, Euro balance, account_type, and account_id fields. For computing the Euro balance,we’ll assume a rate of 1EURO: 1.2USD

For this example, we’ll assume that we’ve already established a connection to MongoDB and initialized the collection object. We’ll use the banking accounts dataset. Here’s an example of a document from the collection that we’ll work with.

We can implement the pipeline by using the $match, $sort, and $project stages.

$match filters incoming documents by the account_type and uses the Filters builder class. This is followed by the $sort and $project stages, which are defined by using the Aggregates builder class. The Projections.computed() method creates a euro_balance field whose value is computed from the given expression.

Within $match, the Filters builder class allows us to specify the balance amount and account type that we want.

Now that all the pipeline stages are defined, we’ll pass the MongoCollection’s aggregate method an array of the aggregation stages that we want to execute.

It's important to note that when we're creating aggregation pipelines, we are explicitly specifying the order of processes. This means that we need to be mindful that our stages are in the intended order.

The aggregate method returns an AggregateIterable<Document>, which we iterate to print the results of the aggregation pipeline.

Well done! In this video, you learned about the $sort and $project stages and how to implement them in an aggregation pipeline by using the Aggregates builder class. You also learned how to $match by using the Filters builder class.

The MongoDB Java driver provides us with a wide range of utility classes to simplify aggregations.