DEV Community

Cover image for Working with MongoDB Aggregation
Dominic Azuka
Dominic Azuka

Posted on

Working with MongoDB Aggregation

๐Ÿš€MongoDB Aggregation ๐Ÿ“Š

Magic of MongoDB Aggregation Framework, combined with the might of Node.js on the server side.

In this series, we'll explore the art of data reshaping, analysis, and insights extraction.
From pipeline magic to sorting, we'll walk through real examples demonstrating how to harness the potential of MongoDB's Aggregation Framework.

1.Pipeline Magic:
๐ŸŒŸ Imagine a pipeline of data stages, each performing a specific operation. That's the MongoDB Aggregation Framework! ๐Ÿง™โ€โ™‚๏ธ String together stages like $match, $group, and $project to craft your data masterpiece. Let's build a pipeline!

const result = await UserModel.aggregate([
  { $match: { age: { $gt: 18 } } },
  { $group: { _id: "$category", total: { $sum: "$price" } } },
  { $project: { _id: 0, category: "$_id", total: 1 } }
]);
console.log(result); // Expected output: [{ category: "electronics", total: 150 }, { category: "clothing", total: 80 }]
// This pipeline filters users above 18, groups them by category, and projects category and total price.
Enter fullscreen mode Exit fullscreen mode

2. Matching Data:
๐ŸŽฏ First up, the $match stage! Think of it as your data filter. ๐Ÿ•ต๏ธโ€โ™‚๏ธ Select only what you need from the vast collection. Let's put on our detective hats and match the data!

const result = await UserModel.aggregate([
  { $match: { age: { $gt: 18 } } }
]);
console.log(result); // Expected output: [{ _id: 1, name: "Alice", age: 25 }, { _id: 2, name: "Bob", age: 30 }]
// This query retrieves users above 18 years old.
Enter fullscreen mode Exit fullscreen mode

3. Grouping:
๐Ÿค Time for the $group stage! Group data by a specific field and perform calculations. It's like bringing together puzzle pieces to see the bigger picture. Let's gather insights through grouping!

const result = await UserModel.aggregate([
  { $group: { _id: "$category", avgAge: { $avg: "$age" } } }
]);
console.log(result); // Expected output: [{ _id: "electronics", avgAge: 27.5 }, { _id: "clothing", avgAge: 28 }]
// This aggregation computes the average age for each category.
Enter fullscreen mode Exit fullscreen mode

4. Projecting:
๐ŸŒˆ The $project stage lets you shape your data dreams! ๐Ÿ’ญ Choose which fields to include or exclude. Mold your data into the perfect form.

const result = await UserModel.aggregate([
  { $project: { name: 1, age: 1, _id: 0 } }
]);
console.log(result); // Expected output: [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }]
// This aggregation projects only the name and age fields.
Enter fullscreen mode Exit fullscreen mode

5. Adding Dimensions:
โž• Introducing the $addFields stage! Imagine adding new dimensions to your data universe. ๐ŸŒŒ Create calculated fields and enrich your insights. Let's explore new dimensions together!

const result = await UserModel.aggregate([
  { $addFields: { birthYear: { $subtract: [2023, "$age"] } } }
]);
console.log(result); // Expected output: [{ _id: 1, name: "Alice", age: 25, birthYear: 1998 }, { _id: 2, name: "Bob", age: 30, birthYear: 1993 }]
//This aggregation calculates and adds a birth year field.
Enter fullscreen mode Exit fullscreen mode

6. Sorting:
๐Ÿ”ข The $sort stage brings order to your data chaos! Arrange documents based on fields of your choice. It's like organizing a library to find books easily.

const result = await UserModel.aggregate([
  { $sort: { age: 1 } }
]);
console.log(result); // Expected output: [{ _id: 1, name: "Alice", age: 25 }, { _id: 2, name: "Bob", age: 30 }]
//This aggregation sorts users by age in ascending order.
Enter fullscreen mode Exit fullscreen mode

7. Unwind:
๐ŸŒ€ Enter the $unwind stageโ€”a gateway to unleashing arrays! Expand array fields into separate documents for deeper analysis. It's like unrolling a scroll of insights.

const result = await UserModel.aggregate([
  { $unwind: "$hobbies" }
]);
console.log(result); // Expected output: [{ _id: 1, name: "Alice", hobbies: "reading" }, { _id: 1, name: "Alice", hobbies: "painting" }, ...]
// This aggregation unwinds the hobbies array into separate documents.
Enter fullscreen mode Exit fullscreen mode

โšก Key Takeaways:

  • Understand the core stages of the MongoDB Aggregation Framework.
  • Learn to filter and shape your data for precise analysis.
  • Gain insights into grouping and projection techniques.
  • Explore the world of adding dimensions to your data.
  • Master the art of sorting and unwinding for comprehensive insights.

๐Ÿ” Disclaimer:
Please note that the code examples above are simplified for educational purposes. In real-world scenarios, you would need to implement additional error handling, security considerations, and follow best practices for secure coding. Also, client-side codes can be achieved with try-catch blocks, and HTTP requests can be handled using libraries like Axios.

Follow Azuka Dominic for more related content.

Top comments (0)