Reader small image

You're reading from  Mastering MongoDB 7.0 - Fourth Edition

Product typeBook
Published inFeb 2024
PublisherPackt
ISBN-139781835883501
Edition4th Edition
Concepts
Right arrow
Authors (7):
Marko Aleksendrić
Marko Aleksendrić
author image
Marko Aleksendrić

Marko Aleksendrić is an analyst, an ex-scientist, and a freelance self-taught web developer with over 20 years of experience. Marko has authored the book Modern Web Development with the FARM Stack, published by Packt Publishing. With a keen interest in backend and frontend development, he has been an avid MongoDB user for the last 15 years for various web and data analytics-related projects, with Python and JavaScript as his main tools.
Read more about Marko Aleksendrić

Arek Borucki
Arek Borucki
author image
Arek Borucki

Arek Borucki, a recognized MongoDB Champion and certified database administrator, has been working with MongoDB technology since 2016. As principal SRE database engineer, he works closely with technologies such as MongoDB, Elasticsearch, PostgreSQL, Kafka, Kubernetes, Terraform, AWS, and GCP. His extensive experience includes working with renowned companies such as Amadeus, Deutsche Bank, IBM, Nokia, and Beamery. Arek is also a Certified Kubernetes Administrator and developer, an active speaker at international conferences, and a co-author of questions for the MongoDB Associate DBA Exam.
Read more about Arek Borucki

Leandro Domingues
Leandro Domingues
author image
Leandro Domingues

Leandro Domingues is a MongoDB Community Champion and a Microsoft Data Platform MVP alumnus. Specializing in NoSQL databases, focusing on MongoDB, he has authored several articles and is also a speaker and organizer of events and conferences. In addition to teaching MongoDB, he was a professor at one of the largest universities in Brazil. Leandro is passionate about MongoDB and is a mentor and an inspiration to many developers and administrators. His efforts make MongoDB a more comprehensible tool for everyone.
Read more about Leandro Domingues

Malak Abu Hammad
Malak Abu Hammad
author image
Malak Abu Hammad

Malak Abu Hammad is a seasoned software engineering manager at Chain Reaction, with a decade of expertise in MongoDB. She has carved a niche for herself not only in MongoDB but also in essential web app technologies. Along with conducting various online and offline workshops, Malak is a MongoDB Champion and a founding member of the MongoDB Arabic Community. Her vision for MongoDB is a future with an emphasis on Arabic localization, aimed at bridging the gap between technology and regional dialects.
Read more about Malak Abu Hammad

Elie Hannouch
Elie Hannouch
author image
Elie Hannouch

Elie Hannouch is a senior software engineer and digital transformation expert. A driving force in the tech industry, he has a proven track record of delivering robust, scalable, and impactful solutions. As a start-up founder, Elie combines his extensive engineering background with strategic innovation to redefine how enterprises operate in today's digital age. Apart from being a MongoDB Champion, Elie leads the MongoDB, Google, and CNCF communities in Lebanon and works toward empowering aspiring tech professionals by demystifying complex concepts and inspiring a new generation of tech enthusiasts.
Read more about Elie Hannouch

Rajesh Nair
Rajesh Nair
author image
Rajesh Nair

Rajesh Nair is a software professional from Kerala, India, with over 12 years of experience working in various MNCs. He started his career as a database administrator for multiple RDBMS technologies, including Progress OpenEdge and MySQL. Rajesh also managed huge datasets for critical applications running on MongoDB as a MongoDB administrator for several years. He has worked on technologies such as MongoDB, AWS, Java, Kafka, MySQL, Progress OpenEdge, shell scripting, and Linux administration. Rajesh is currently based out of Amsterdam, Netherlands, working as a senior software engineer.
Read more about Rajesh Nair

Rachelle Palmer
Rachelle Palmer
author image
Rachelle Palmer

Rachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the director of the technical services engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.
Read more about Rachelle Palmer

View More author details
Right arrow

Aggregation

Aggregations in MongoDB are operations consisting of several steps that process multiple documents and return computed results. Aggregations are built around the concept of pipelines, through which data flows are gradually processed. In a pipeline, the output from the current processing unit is fed as input to the next unit (similar to chaining commands in Linux or a data-wrangling script in Python). In a pipeline, at each stage, a set of documents is fed to the processing unit's input and the output is fed to the following unit. This process ultimately provides solutions to potentially complex problems by breaking them down into smaller and simpler stages.

In this chapter, you will dive deeper into some of the more interesting and useful features of the MongoDB aggregation framework.

This chapter will cover the following topics:

  • The purpose of the MongoDB aggregation framework
  • Principles of aggregation and aggregation stages
  • Basic aggregation...

Technical requirements

To perform the exercises covered in this chapter, you will need the following:

  • A computer running macOS, Windows, or Linux
  • MongoDB Compass – the GUI MongoDB client
  • A MongoDB Atlas account

Connect to your Atlas account and enable the sample datasets that ship with Atlas. For instructions on connecting to your MongoDB database, please refer to Chapter 4, Connecting to MongoDB.

If you prefer the GUI tool, make sure to also download MongoDB Compass from the MongoDB website: https://www.mongodb.com/try/download/compass.

Now that you have your system set up, you are ready to begin exploring the MongoDB aggregation framework.

MongoDB aggregation framework

The MongoDB aggregation framework allows you to fine tune and process complex data on the server, drastically reducing the amount of data that is transferred to the application for further processing. The aggregation framework is an incredibly powerful data processing workhorse that enables you to:

  • Handle custom data presentations through views
  • Join data from different collections
  • Perform data science tasks, such as data wrangling and analysis
  • Handle big data
  • Run real-time analytics, monitor data, and create dashboards

MongoDB is centered around the concept that data should be easily retrievable and accessible to fit your application. As shown in Chapter 7, Advanced Querying in MongoDB, the querying framework—with its tunable parameters—is powerful. However, it may not always provide the precise data in the required shape or format. It may also lack the accompanying descriptive statistics that are frequently...

Basic aggregation operators

At this point, you should be familiar with the basic MongoDB stages used for querying ($match, $limit, $search, $sample, $skip, $sort, etc.), mutating ($fill, $project, $set, $unset, and others), summarizing ($group, $count, etc.), joining, and performing input/output operations on documents.

For a quick refresher, the MongoDB documentation provides an excellent starting point: https://www.mongodb.com/docs/v7.0/reference/operator/aggregation/.

Bitwise operators in aggregation

One of the new features in MongoDB 7.0 is the introduction of bitwise operators in aggregations. Bitwise operators are especially useful in cases where documents have a lot of bit-mask values (such as status, permission settings, or general settings).

There are four operators that allow developers to create aggregations based on bit-mask values:

  • $bitAnd: Returns the result of a bitwise and operation on an array of integers or long values
  • $bitOr: Returns the result...

Best practices

Writing and specifying good aggregations takes practice, and throughout this chapter, you have focused on some useful principles. The aggregation pipeline is a sequential set of stages, and it encourages high composability and modularity. Here are some best practices that you can keep in mind when using MongoDB aggregations:

Code modularity

No matter how complex an aggregation gets, it can and should always be broken down into simple, understandable stages that can be tested in isolation, reducing the cognitive load on the developer. If you're using Compass for prototyping your aggregations, there is an option for turning down certain stages without removing them. If you're coding in an editor, it's easier if the stages are separated, with an option to toggle the comments. The Visual Studio Code extension, introduced earlier in this book, is an excellent tool for debugging, analyzing, and synthesizing aggregation pipelines.

Finally, with JavaScript...

Summary

In this chapter, you delved deeply into the aggregation framework, exploring the possibilities and understanding how various stages and expression operators can be employed to tackle a wide range of problems.

You learned about aggregation stages and operators, examining real-life databases from Atlas that effectively demonstrate essential functionalities. The chapter included valuable tips and suggestions designed to make you proficient as quickly as possible, with a focus on practical and advanced functionalities.

In the next chapter, you will see how MongoDB handles multi-document ACID transactions, and the significance this concept has in sectors with strict requirements, such as finance, fintech, and mission-critical applications.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering MongoDB 7.0 - Fourth Edition
Published in: Feb 2024Publisher: PacktISBN-13: 9781835883501
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (7)

author image
Marko Aleksendrić

Marko Aleksendrić is an analyst, an ex-scientist, and a freelance self-taught web developer with over 20 years of experience. Marko has authored the book Modern Web Development with the FARM Stack, published by Packt Publishing. With a keen interest in backend and frontend development, he has been an avid MongoDB user for the last 15 years for various web and data analytics-related projects, with Python and JavaScript as his main tools.
Read more about Marko Aleksendrić

author image
Arek Borucki

Arek Borucki, a recognized MongoDB Champion and certified database administrator, has been working with MongoDB technology since 2016. As principal SRE database engineer, he works closely with technologies such as MongoDB, Elasticsearch, PostgreSQL, Kafka, Kubernetes, Terraform, AWS, and GCP. His extensive experience includes working with renowned companies such as Amadeus, Deutsche Bank, IBM, Nokia, and Beamery. Arek is also a Certified Kubernetes Administrator and developer, an active speaker at international conferences, and a co-author of questions for the MongoDB Associate DBA Exam.
Read more about Arek Borucki

author image
Leandro Domingues

Leandro Domingues is a MongoDB Community Champion and a Microsoft Data Platform MVP alumnus. Specializing in NoSQL databases, focusing on MongoDB, he has authored several articles and is also a speaker and organizer of events and conferences. In addition to teaching MongoDB, he was a professor at one of the largest universities in Brazil. Leandro is passionate about MongoDB and is a mentor and an inspiration to many developers and administrators. His efforts make MongoDB a more comprehensible tool for everyone.
Read more about Leandro Domingues

author image
Malak Abu Hammad

Malak Abu Hammad is a seasoned software engineering manager at Chain Reaction, with a decade of expertise in MongoDB. She has carved a niche for herself not only in MongoDB but also in essential web app technologies. Along with conducting various online and offline workshops, Malak is a MongoDB Champion and a founding member of the MongoDB Arabic Community. Her vision for MongoDB is a future with an emphasis on Arabic localization, aimed at bridging the gap between technology and regional dialects.
Read more about Malak Abu Hammad

author image
Elie Hannouch

Elie Hannouch is a senior software engineer and digital transformation expert. A driving force in the tech industry, he has a proven track record of delivering robust, scalable, and impactful solutions. As a start-up founder, Elie combines his extensive engineering background with strategic innovation to redefine how enterprises operate in today's digital age. Apart from being a MongoDB Champion, Elie leads the MongoDB, Google, and CNCF communities in Lebanon and works toward empowering aspiring tech professionals by demystifying complex concepts and inspiring a new generation of tech enthusiasts.
Read more about Elie Hannouch

author image
Rajesh Nair

Rajesh Nair is a software professional from Kerala, India, with over 12 years of experience working in various MNCs. He started his career as a database administrator for multiple RDBMS technologies, including Progress OpenEdge and MySQL. Rajesh also managed huge datasets for critical applications running on MongoDB as a MongoDB administrator for several years. He has worked on technologies such as MongoDB, AWS, Java, Kafka, MySQL, Progress OpenEdge, shell scripting, and Linux administration. Rajesh is currently based out of Amsterdam, Netherlands, working as a senior software engineer.
Read more about Rajesh Nair

author image
Rachelle Palmer

Rachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the director of the technical services engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.
Read more about Rachelle Palmer