Example of aggregation pipeline with MongoDB ,Nodejs.

Moatez Bejaoui
eDonec
Published in
2 min readMay 24, 2021

In this topic, I will be talking about the aggregation pipeline in MongoDB and how good they are with having an example of how to use them.

Introduction

The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into aggregated results.

Aggregation pipeline

If you wanna read about what stages you can use check this link.

Issue

I will be taking an example of a list of countries and manipulate them to a wanted result using the aggregations.

As you can see here, we will be having a list of countries in this form we will be manipulating it using the aggregations in so many ways so bear with me.

1-grouping these countries with their region, returning a count of countries in that region and also showing what the countries are with their states and cities!

2- Returning a list of countries in a form of Country, city.

countrys list with states and their cities

1 — Grouping countries with their region.

Result :

2 — Returning a list of countries in a form of Country, city.

Result :

Q&A

If something doesn’t work as expected or needs more details, just drop a comment below :) Happy coding!

This has been developed by myself at eDonec.

--

--