Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 8: MongoDB Aggregation — Average Age by City

Lesson 9 of 13 in the free Web Technology Lab (BCS552) notes on Siksha Sarovar, written by Rohit Jangra.

Program Statement

Develop a script that uses MongoDB's aggregation framework to perform operations like grouping, filtering, and sorting. For instance, aggregate user data to find the average age of users in different cities.

The Real MongoDB Aggregation Pipeline

Run this in mongosh after inserting sample documents into a users collection:

db.users.insertMany([
  { name: "Aman",  city: "Delhi",     age: 22 },
  { name: "Riya",  city: "Mumbai",    age: 27 },
  { name: "Kabir", city: "Delhi",     age: 30 },
  { name: "Sneha", city: "Bengaluru", age: 24 },
  { name: "Zoya",  city: "Mumbai",    age: 21 },
  { name: "Dev",   city: "Bengaluru", age: 29 }
]);

db.users.aggregate([
  { $group: { _id: "$city", avgAge: { $avg: "$age" } } },
  { $sort:  { avgAge: -1 } }
]);

Stages Used

StagePurpose
$groupBuckets documents by city, computing $avg per bucket
$sortOrders the grouped results (here, highest average age first)

Note

MongoDB needs a running mongod server — see Lab 0. The code below simulates the exact same pipeline in plain JavaScript over an in-memory array, so you can run it right now and see the identical grouped/sorted result.

CO Mapping

CO4