Welcome to our deep dive into MongoDB Aggregation! In this lesson, we'll explore this powerful feature that enables you to perform complex data analysis and manipulation, all within MongoDB. By the end of this tutorial, you'll be ready to take your Node.js applications to the next level. 💡
MongoDB Aggregation is a pipeline-based processing system that processes data records to produce aggregated results. It's similar to SQL's GROUP BY or JOIN statements but provides more flexibility and scalability.
To use MongoDB Aggregation in Node.js, we'll need the mongodb package. You can install it using npm:
npm install mongodb
Now, let's connect to a MongoDB database:
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const dbName = 'testDB';
let client;
async function connectToDB() {
client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
return client.db(dbName);
}Let's assume we have a collection called users containing documents like this:
{ "_id": 1, "name": "John", "age": 25 }
{ "_id": 2, "name": "Jane", "age": 30 }Now, let's find the average age of the users:
async function getAverageAge() {
const db = await connectToDB();
const pipeline = [
{ $group: { _id: null, average_age: { $avg: '$age' } } },
];
const cursor = db.collection('users').aggregate(pipeline);
const result = await cursor.toArray();
console.log(result); // Output: [ { average_age: 27.5 } ]
}
getAverageAge();In this example, we've used a simple aggregation pipeline with a $group stage to find the average age. 💡 Pro Tip: The $ symbol is used to refer to the field names in each document.
Here are some additional stages you can use in MongoDB Aggregation:
$match: Filters documents that match a specific condition$sort: Sorts documents in the pipeline$project: Transforms and selects documents' fields$lookup: Joins collections based on a common field$lookup with $match: Performs a join with a filtered sub-collectionWhat does the `$group` stage in MongoDB Aggregation do?
That's it for now! As you continue learning, you'll discover even more stages and capabilities of MongoDB Aggregation. Happy coding! 🎉