π Mongoose Aggregation & Aggregation Pipeline (Well-Structured Notes with Examples)
π¨βπ» Developer.WK </>
March 1, 2025
π Mongoose Aggregation & Aggregation Pipeline
Well-Structured Notes with Examples
π Introduction to Mongoose Aggregation
Mongoose provides an aggregation framework to perform advanced data processing on MongoDB collections. Aggregation allows grouping, filtering, sorting, transforming, and analyzing data efficiently.
π Key Features of Aggregation
Processes large amounts of data in a single query.
Supports grouping, filtering, sorting, and transforming data.
Reduces the need for multiple queries.
Improves performance by reducing network overhead.
π Aggregation Pipeline in Mongoose
The Aggregation Pipeline is a sequence of stages that process documents. Each stage takes input, processes it, and passes the output to the next stage.
π Common Aggregation Stages
Stage
Description
$match
Filters documents based on conditions (like find()).
$group
Groups documents by a specified field and performs operations like sum, avg, min, max, etc.
$project
Specifies which fields to include or exclude.
$sort
Sorts documents based on field values.
$limit
Limits the number of documents returned.
$skip
Skips a specified number of documents.
$lookup
Performs joins between collections.
$unwind
Deconstructs an array field into separate documents.
5οΈβ£ Using $lookup - Join Users with Orders Collection
const usersWithOrders =awaitUser.aggregate([{$lookup:{from:"orders",// Collection to joinlocalField:"_id",// Field in 'users'foreignField:"userId",// Field in 'orders'as:"orders"// Output array field}}]);console.log(usersWithOrders);
Output: Each user document will have an orders array.
Output: Only users with salary β₯ 6000 will be shown.
1οΈβ£1οΈβ£ Using $bucket - Group Users into Age Ranges
Group users into different age brackets:
const ageGroups =awaitUser.aggregate([{$bucket:{groupBy:"$age",boundaries:[20,30,40],// Age ranges (20-29, 30-39)default:"40+",// Group ages 40+ into oneoutput:{count:{$sum:1},avgSalary:{$avg:"$salary"}}}}]);console.log(ageGroups);
Output: Groups users into 20-29, 30-39, and 40+ categories.
1οΈβ£2οΈβ£ Using $out - Save Aggregation Result in a New Collection
Store the aggregated result into a new MongoDB collection:
awaitUser.aggregate([{$group:{_id:"$city",totalUsers:{$sum:1}}},{$out:"user_summary"}// Creates a new collection named 'user_summary']);
Output: A new user_summary collection is created in the database.
1οΈβ£3οΈβ£ Using $merge - Merge Aggregated Data into an Existing Collection
Output: Merges results into city_salary_summary collection.
π― When to Use Aggregation?
Data transformation (e.g., adding new computed fields).
Filtering and grouping (e.g., by age, city, etc.).
Joining collections (e.g., users and orders).
Generating reports (e.g., average salary per city).
Optimizing performance by reducing multiple queries.
π₯ Advanced Mongoose Aggregation Examples
1οΈβ£4οΈβ£ Using $text - Full-Text Search
Perform full-text search using a text index:
// Step 1: Create a Text IndexawaitUser.collection.createIndex({name:"text",city:"text"});// Step 2: Search for Users Matching a Keywordconst searchResults =awaitUser.aggregate([{$match:{$text:{$search:"New York"}}}]);console.log(searchResults);
Output: Finds users whose name or city contains "New York".
1οΈβ£5οΈβ£ Using $sample - Get Random Users
Fetch random users:
const randomUsers =awaitUser.aggregate([{$sample:{size:2}}// Get 2 random users]);console.log(randomUsers);
2οΈβ£1οΈβ£ Using $geoNear - Find Users Near a Location
Find users near New York:
const nearbyUsers =awaitUser.aggregate([{$geoNear:{near:{type:"Point",coordinates:[-73.935242,40.730610]},// New YorkdistanceField:"distanceFromNY",spherical:true}}]);console.log(nearbyUsers);
Output: Lists users sorted by distance from New York.
π― Key Takeaways
β $text β Full-text search.
β $sample β Get random documents.
β $expr β Compare two fields.
β $map β Modify array elements.
β $filter β Filter array elements.
β $setWindowFields β Ranking & running totals.
β $dateFromString β Convert string to date.
β $geoNear β Find nearest locations.
π Final Thoughts
These advanced aggregation techniques allow data transformation, ranking, text search, and geospatial queries. Use them to unlock the full potential of MongoDB's aggregation framework!