Summarize MongoDB Data

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to perform basic aggregation operations in MongoDB, including calculating totals, finding minimum and maximum values, counting documents, calculating averages, and generating reports. The lab covers practical examples using a sample book collection, demonstrating the power of MongoDB's aggregation framework to extract meaningful insights from your data.

The lab guides you through step-by-step instructions, starting with calculating total values, such as the total book value and total quantity. You'll then learn how to find the minimum and maximum book prices, count the number of documents, and calculate the average book price. Finally, you'll explore generating reports to summarize the data in your collection.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/AggregationOperationsGroup(["`Aggregation Operations`"]) mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("`Project Fields`") mongodb/AggregationOperationsGroup -.-> mongodb/group_documents("`Group Documents`") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("`Aggregate Group Totals`") subgraph Lab Skills mongodb/find_documents -.-> lab-422093{{"`Summarize MongoDB Data`"}} mongodb/query_with_conditions -.-> lab-422093{{"`Summarize MongoDB Data`"}} mongodb/project_fields -.-> lab-422093{{"`Summarize MongoDB Data`"}} mongodb/group_documents -.-> lab-422093{{"`Summarize MongoDB Data`"}} mongodb/aggregate_group_totals -.-> lab-422093{{"`Summarize MongoDB Data`"}} end

Calculate Totals

In this step, you'll learn how to calculate total values using MongoDB's aggregation framework. We'll use a sample book collection to demonstrate how to sum up numerical fields.

First, let's start the MongoDB shell and create a sample book collection:

mongosh

Now, let's create a collection of books with prices:

use bookstore

db.books.insertMany([
    { title: "Python Basics", price: 29.99, quantity: 50 },
    { title: "MongoDB Essentials", price: 39.99, quantity: 30 },
    { title: "Data Science Guide", price: 45.50, quantity: 25 },
    { title: "Web Development", price: 34.75, quantity: 40 }
])

To calculate the total value of all books, we'll use the $sum aggregation operator:

db.books.aggregate([
  {
    $group: {
      _id: null,
      totalBookValue: { $sum: { $multiply: ["$price", "$quantity"] } }
    }
  }
]);

Example output:

[
  {
    _id: null,
    totalBookValue: 5197.25
  }
]

Let's break down what this aggregation does:

  • $group groups all documents together
  • _id: null means we're aggregating the entire collection
  • $multiply calculates the total value for each book (price * quantity)
  • $sum adds up all these values

You can also calculate other totals, like the total number of books:

db.books.aggregate([
  {
    $group: {
      _id: null,
      totalQuantity: { $sum: "$quantity" }
    }
  }
]);

Example output:

[
  {
    _id: null,
    totalQuantity: 145
  }
]

Find Min Max Values

In this step, you'll learn how to find minimum and maximum values using MongoDB's aggregation framework. We'll continue using our bookstore collection from the previous step.

Let's first verify our existing collection:

use bookstore
db.books.find()

To find the minimum and maximum book prices, we'll use the $min and $max aggregation operators:

db.books.aggregate([
  {
    $group: {
      _id: null,
      lowestPrice: { $min: "$price" },
      highestPrice: { $max: "$price" }
    }
  }
]);

Example output:

[
  {
    _id: null,
    lowestPrice: 29.99,
    highestPrice: 45.50
  }
]

We can also find the minimum and maximum quantities:

db.books.aggregate([
  {
    $group: {
      _id: null,
      lowestQuantity: { $min: "$quantity" },
      highestQuantity: { $max: "$quantity" }
    }
  }
]);

Example output:

[
  {
    _id: null,
    lowestQuantity: 25,
    highestQuantity: 50
  }
]

For more detailed insights, we can find the book with the lowest and highest prices:

db.books.aggregate([
  {
    $sort: { price: 1 }
  },
  {
    $limit: 1
  },
  {
    $project: {
      title: 1,
      price: 1
    }
  }
]);

Example output:

[
  {
    _id: ObjectId("..."),
    title: "Python Basics",
    price: 29.99
  }
]

Count Documents

In this step, you'll learn different methods to count documents in MongoDB using various techniques. We'll continue working with our bookstore collection from previous steps.

First, let's verify our existing collection:

use bookstore
db.books.find()

There are multiple ways to count documents in MongoDB. Let's explore them:

  1. Basic Count Method:
db.books.countDocuments();

Example output:

4
  1. Counting Documents with a Filter:
db.books.countDocuments({ price: { $gt: 35 } });

This counts books with a price greater than 35.

Example output:

2
  1. Using Aggregation Framework for Counting:
db.books.aggregate([
  {
    $match: { quantity: { $gte: 30 } }
  },
  {
    $count: "booksWithHighQuantity"
  }
]);

This counts books with quantity greater than or equal to 30.

Example output:

[
  {
    booksWithHighQuantity: 3
  }
]
  1. Counting Unique Values:
db.books.aggregate([
  {
    $group: {
      _id: "$title",
      count: { $sum: 1 }
    }
  }
]);

This shows how many times each book title appears.

Example output:

[
  {
    _id: "Python Basics",
    count: 1
  },
  ...
]

Calculate Averages

In this step, you'll learn how to calculate average values using MongoDB's aggregation framework. We'll continue working with our bookstore collection from previous steps.

First, let's verify our existing collection:

use bookstore
db.books.find()
  1. Calculate Average Book Price:
db.books.aggregate([
  {
    $group: {
      _id: null,
      averagePrice: { $avg: "$price" }
    }
  }
]);

Example output:

[
  {
    _id: null,
    averagePrice: 37.56
  }
]
  1. Calculate Average Quantity with Rounding:
db.books.aggregate([
  {
    $group: {
      _id: null,
      averageQuantity: { $avg: "$quantity" }
    }
  },
  {
    $project: {
      averageQuantity: { $round: ["$averageQuantity", 2] }
    }
  }
]);

Example output:

[
  {
    _id: null,
    averageQuantity: 36.25
  }
]
  1. Average Price by Conditional Grouping:
db.books.aggregate([
  {
    $group: {
      _id: {
        priceCategory: {
          $switch: {
            branches: [
              { case: { $lt: ["$price", 35] }, then: "Budget" },
              { case: { $gte: ["$price", 35] }, then: "Premium" }
            ]
          }
        }
      },
      averagePrice: { $avg: "$price" }
    }
  }
]);

Example output:

[
  {
    _id: { priceCategory: "Budget" },
    averagePrice: 32.37
  },
  {
    _id: { priceCategory: "Premium" },
    averagePrice: 42.75
  }
]

Generate Reports

In this final step, you'll learn how to generate more complex reports using MongoDB's aggregation framework. We'll combine multiple aggregation stages to create insightful reports from our bookstore collection.

First, let's verify our existing collection:

use bookstore
db.books.find()
  1. Comprehensive Book Inventory Report:
db.books.aggregate([
  {
    $project: {
      title: 1,
      totalValue: { $multiply: ["$price", "$quantity"] },
      inventoryStatus: {
        $switch: {
          branches: [
            { case: { $lt: ["$quantity", 30] }, then: "Low Stock" },
            { case: { $gte: ["$quantity", 30] }, then: "In Stock" }
          ]
        }
      }
    }
  },
  {
    $sort: { totalValue: -1 }
  }
]);

Example output:

[
  {
    _id: ObjectId("..."),
    title: "Python Basics",
    totalValue: 1499.50,
    inventoryStatus: "In Stock"
  },
  ...
]
  1. Price Range Distribution Report:
db.books.aggregate([
  {
    $bucket: {
      groupBy: "$price",
      boundaries: [0, 35, 45, 100],
      default: "Other",
      output: {
        count: { $sum: 1 },
        titles: { $push: "$title" }
      }
    }
  }
]);

Example output:

[
  {
    _id: 0,
    count: 2,
    titles: ["Python Basics", "Web Development"]
  },
  {
    _id: 35,
    count: 1,
    titles: ["MongoDB Essentials"]
  },
  ...
]
  1. Detailed Sales Performance Report:
db.books.aggregate([
  {
    $group: {
      _id: {
        priceCategory: {
          $switch: {
            branches: [
              { case: { $lt: ["$price", 35] }, then: "Budget" },
              { case: { $gte: ["$price", 35] }, then: "Premium" }
            ]
          }
        }
      },
      totalBooks: { $sum: 1 },
      totalQuantity: { $sum: "$quantity" },
      totalValue: { $sum: { $multiply: ["$price", "$quantity"] } },
      avgPrice: { $avg: "$price" }
    }
  },
  {
    $project: {
      _id: 0,
      priceCategory: "$_id.priceCategory",
      totalBooks: 1,
      totalQuantity: 1,
      totalValue: { $round: ["$totalValue", 2] },
      avgPrice: { $round: ["$avgPrice", 2] }
    }
  }
]);

Example output:

[
  {
    priceCategory: "Budget",
    totalBooks: 2,
    totalQuantity: 90,
    totalValue: 2984.50,
    avgPrice: 32.37
  },
  {
    priceCategory: "Premium",
    totalBooks: 2,
    totalQuantity: 55,
    totalValue: 2212.75,
    avgPrice: 42.75
  }
]

Summary

In this lab, you will learn how to calculate totals, find minimum and maximum values, count documents, calculate averages, and generate reports using MongoDB's aggregation framework. First, you will calculate the total value of all books in a sample book collection by using the $sum aggregation operator. You will also learn how to calculate the total number of books. Next, you will find the minimum and maximum book prices using the $min and $max aggregation operators. You will then learn how to count the number of documents in the collection and calculate the average book price.

Other MongoDB Tutorials you may like