DEV Community

loading...

The Beginner's Guide To MongoDB Aggregation Pipeline Part 1

cpuram1 profile image CALVIN JOB PURAM ・2 min read

In this series, I will try to demystify the MongoDB Aggregation framework which is a powerful tool that MongoDB offers and gives you great instruments to work with documents in your collection. Using the aggregation framework, you can easily group documents in your collection by specific conditions. you can also add additional fields during grouping such as average, total, minimum, maximum and so on. You can process documents in your collection in several stages one by one. Aggregation request is very fast and you can get results very quickly. I will start this series with some theoretical stuff to aid our understanding before we dive into looking at some examples. We will look into different aggregation requests on our collections and you will see the full power of the MongoDB aggregation framework.

We need a sample collection to perform this aggregation requests. I have provided an array of documents Here which you can copy the documents.

db.names.insertMany(documents)
Enter fullscreen mode Exit fullscreen mode

make sure you create a database run the above command replace the "documents" with the array of data you copy from the gist. I will assume that you have worked with MongoDB performing basic CRUD operations, and you have MongoDB setup and installed in your system.

Aggregation Process

Alt Text

Suppose we have some documents at the beginning of the aggregation, first we can perform match operation. This match query can produce a subset of the documents. Then, you can take the subset of that document and perform a group operation. As a result of the group operation, you will get brand new documents. These documents are matched and grouped based on certain conditions. for example you may want to match documents based on countries of persons in your collections and you may want to group them based on gender. So in a nutshell aggregation is just like a pipeline in which we have a large set of documents that passes through various stages and these documents get evaluated based on the conditions you placed on them till you have a new set of documents that matched the criteria. This is just a high-level overview. Later in these series, we will dive deeper into details of what it entails.

Discussion (0)

Forem Open with the Forem app