QA
Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

❓ Interview Prompt: Demonstrate a multi-stage aggregation pipeline joining collections and computing analytics with Mongoose.

The MongoDB Aggregation Pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms documents into aggregated results.

Common Stages:

•
$match: Filters documents (uses indexes).
•
$lookup: Performs left outer join with another collection.
•
$group: Groups documents by specified key and performs accumulators ($sum, $avg).
•
$project: Reshapes output documents.

Code Implementation Example

typescript
import { OrderModel } from './models/Order';

async function getCustomerTotalSpend() {
  const result = await OrderModel.aggregate([
    { $match: { status: 'COMPLETED' } },
    {
      $lookup: {
        from: 'users',
        localField: 'userId',
        foreignField: '_id',
        as: 'userInfo'
      }
    },
    { $unwind: '$userInfo' },
    {
      $group: {
        _id: '$userId',
        customerName: { $first: '$userInfo.name' },
        totalSpent: { $sum: '$totalAmount' },
        orderCount: { $sum: 1 }
      }
    },
    { $sort: { totalSpent: -1 } }
  ]);

  return result;
}
💡MongoDB multi-stage aggregation pipeline with Mongoose.
🎯 Interview Key Takeaway

Place $match at the start of aggregation pipelines to leverage MongoDB indexes and reduce downstream pipeline processing size.

#MongoDB#Mongoose#Aggregation#Database#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?

Beginner LevelMongoDB & Mongoose

How do basic CRUD operations work in MongoDB (find, insertOne, updateOne, deleteOne)?