0
0
MongodbHow-ToBeginner · 3 min read

How to Use Aggregate in Mongoose: Syntax and Examples

In Mongoose, use the aggregate() method on a model to perform aggregation pipelines for complex data processing. Pass an array of stages like $match, $group, and $sort to define the operations. The method returns a promise with the aggregated results.
📐

Syntax

The aggregate() method takes an array of pipeline stages. Each stage is an object that specifies an operation like filtering, grouping, or sorting.

  • Model.aggregate(pipelineArray): Runs the aggregation pipeline on the model's collection.
  • pipelineArray: An array of stages such as { $match: { field: value } } to filter documents.
  • Returns a promise that resolves to the aggregation results.
javascript
Model.aggregate([
  { $match: { field: value } },
  { $group: { _id: "$field", total: { $sum: 1 } } },
  { $sort: { total: -1 } }
])
💻

Example

This example shows how to use aggregate() to count how many users belong to each age group and sort the results by count descending.

javascript
const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

async function runAggregation() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  // Sample aggregation pipeline
  const results = await User.aggregate([
    { $match: { age: { $gte: 18 } } },
    { $group: { _id: "$age", count: { $sum: 1 } } },
    { $sort: { count: -1 } }
  ]);

  console.log(results);
  await mongoose.disconnect();
}

runAggregation();
Output
[ { _id: 25, count: 4 }, { _id: 30, count: 2 }, { _id: 18, count: 1 } ]
⚠️

Common Pitfalls

Common mistakes when using aggregate() include:

  • Not using an array for the pipeline stages.
  • Forgetting to prefix field names with $ inside stages like $group.
  • Assuming aggregate() returns a Mongoose document instead of plain objects.
  • Not handling the promise returned by aggregate().

Example of a wrong and right usage:

javascript
// Wrong: pipeline is not an array
Model.aggregate({ $match: { age: { $gt: 20 } } });

// Right: pipeline is an array
Model.aggregate([{ $match: { age: { $gt: 20 } } }]);
📊

Quick Reference

Remember these key points when using aggregate():

  • Pipeline is an array of stages.
  • Stages include $match, $group, $sort, $project, etc.
  • Field names in stages often need $ prefix.
  • Returns a promise with plain JavaScript objects.

Key Takeaways

Use aggregate() with an array of pipeline stages to perform complex queries in Mongoose.
Each stage in the pipeline defines a step like filtering, grouping, or sorting documents.
Always prefix field names with $ inside aggregation operators like $group.
The aggregate() method returns a promise that resolves to plain objects, not Mongoose documents.
Handle the promise properly with async/await or .then() to get the results.