MongoDB / Aggregation in MongoDB

Basic Aggregation

This tutorial will introduce you to the basic concepts of MongoDB aggregation. You'll learn how to use different stages of the aggregation pipeline to transform your documents.

Tutorial 1 of 4 4 resources in this section

Section overview

4 resources

Covers the aggregation framework in MongoDB for processing and transforming data.

1. Introduction

  • Goal: This tutorial aims to introduce you to the basic concepts of MongoDB aggregation. Aggregation operations process data records and return computed results. Aggregation in MongoDB is handled via the aggregation pipeline.
  • Learning Outcome: By the end of this tutorial, you will understand the basic concepts of MongoDB aggregation and how to use different stages of the aggregation pipeline to transform your documents.
  • Prerequisites: Basic knowledge of MongoDB and JavaScript is required. Familiarity with MongoDB's query language would also be beneficial.

2. Step-by-Step Guide

2.1 Aggregation Pipeline

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 an aggregated result. Each stage of the pipeline processes the documents as they pass along from one stage to another.

2.2 Pipeline Operators

Pipeline operators provide tools to perform operations like sorting, grouping, and calculating aggregate values. Here are some common operators:

  1. $match - Filters the documents to pass only documents that match the specified condition(s) to the next pipeline stage.
  2. $group - Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group.
  3. $sum - Calculates and returns the sum of numeric values. $sum can be used in $group stage.
  4. $sort - Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified.

3. Code Examples

3.1 Using $match and $group

// Consider a collection with the following documents
[
  { "_id": 1, "item": "apple", "price": 1, "quantity": 5 },
  { "_id": 2, "item": "banana", "price": 1.5, "quantity": 5 },
  { "_id": 3, "item": "apple", "price": 1, "quantity": 10 },
  { "_id": 4, "item": "banana", "price": 1.5, "quantity": 7 }
]

// Aggregation query
db.collection.aggregate([
  { $match: { item: "apple" } },
  { 
    $group: {
      _id: "$item", 
      total: { $sum: { $multiply: [ "$price", "$quantity" ] } } 
    }
  }
])

// Here, $match filters out only documents where item is 'apple'.
// Then, $group groups these filtered documents by 'item' and calculates the total cost.

Expected Result:

[
  { "_id": "apple", "total": 15 }
]

4. Summary

You have learned the basic concepts of MongoDB aggregation and how to use different stages of the aggregation pipeline. Continue practicing these concepts and try out different aggregation operations.

5. Practice Exercises

  1. Given a collection of students with fields "name", "age", and "grade", write an aggregation query to find the average grade of students over the age of 15.
  2. Given a collection of products with fields "product_name", "price", and "quantity", write an aggregation query to find the total value of each product (price * quantity).

Solutions:

db.students.aggregate([
  { $match: { age: { $gt: 15 } } },
  { $group: { _id: "$name", avgGrade: { $avg: "$grade" } } }
])

Here, we first filter students over the age of 15. Then, we group by name and calculate the average grade.

db.products.aggregate([
  { $group: { _id: "$product_name", totalValue: { $sum: { $multiply: ["$price", "$quantity"] } } } }
])

We group by product_name and calculate the total value of each product by multiplying price and quantity, then summing them up.

Keep practicing with different operators and complex queries to become proficient in MongoDB aggregation.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help