Sling Academy
Home/Node.js/Mongoose Aggregation: Min, Max, Average, Sum, Count

Mongoose Aggregation: Min, Max, Average, Sum, Count

Last updated: December 30, 2023

Introduction

Mastering data aggregation is a crucial skill when dealing with MongoDB through Mongoose, a popular Object Document Mapper for Node.js. By leveraging the power of MongoDB’s aggregation pipeline, developers can perform complex data analysis directly on the database level. This tutorial will offer a comprehensive guide to the fundamental aggregation operations such as computing the minimum (min), maximum (max), average, sum, and count values across data sets using Mongoose.

Setting up the Environment

Before diving into these operations, ensure that you have Node.js and Mongoose installed. Install Mongoose in your project using npm.

npm install mongoose

Connect Mongoose to your MongoDB database:

import mongoose from 'mongoose';

const databaseUri = 'mongodb://localhost:27017/mydatabase';

mongoose.connect(databaseUri, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database connected'))
  .catch(err => console.error('Connection error', err));

Basics of Aggregation

Aggregation in Mongoose is handled through aggregation pipelines. An aggregation pipeline is a set of stages, each manipulating the data as it passes through them.

const result = await Model.aggregate([{ /* stage1 */ }, { /* stage2 */ }]); 

The simplest form of aggregation is counting documents in a collection:

const count = await Model.countDocuments();
console.log(`There are ${count} documents.`);

Computing Minimum and Maximum Values

To compute the minimum or maximum value of a field across all documents:

const minResult = await Model.aggregate([
  { $group: {
    _id: null,
    minField: { $min: '$field' }
  } }
]);
const maxResult = await Model.aggregate([
  { $group: {
   _id: null,
    maxField: { $max: '$field' }
  } }
]);

console.log(`Minimum value: ${minResult[0].minField}`);
console.log(`Maximum value: ${maxResult[0].maxField}`);

Calculating Aggregate Sum

For calculating the sum of all values in a field:

const sumResult = await Model.aggregate([
  { $group: {
    _id: null,
    totalSum: { $sum: '$numericField' }
  }}
]);
console.log(`Total sum of the field: ${sumResult[0].totalSum}`);

Finding the Average Value

To calculate the average value of a field across documents, use $avg:

const avgResult = await Model.aggregate([
  { $group: {
    _id: null,
    avgValue: { $avg: '$numericField' }
  }}
]);
console.log(`Average value: ${avgResult[0].avgValue}`);

Advanced Aggregation Concepts

Moving beyond basics, you might want to filter specific documents or manipulate the datasets further. This can be done using match and project stages.

const advancedResult = await Model.aggregate([
  { $match: { status: 'active' }},
  { $group: {
    _id: '$category',
    avgPrice: { $avg: '$price' }
  }},
  { $project: { _id: 0, category: '$_id', avgPrice: 1 }}
]);
console.log(advancedResult);

Always handle errors to avoid crashing your application. The aggregation operation can be resource-intensive, use indexes appropriately to improve performance.

Summary

In conclusion, using Mongoose aggregation functions such as min, max, average, sum, and count is quintessential for database data processing and analysis. Starting from fundamental concepts and gradually moving to advanced techniques, this tutorial has demonstrated aggregate operations within a Mongoose context using modern JavaScript features. Remember to approach data aggregation carefully, with an eye on impact and performance for production-ready applications.

Next Article: How to Set Unsigned Integer Field in Mongoose

Previous Article: Mongoose: Search documents by keywords (text search)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates