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

Updated: December 30, 2023 By: Guest Contributor Post a comment

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.