MongoDB– Commands and Aggregation
1. Creating a Database
use collegeDB
Explanation:
This command creates or switches to a database named collegeDB. In MongoDB, databases are created
lazily — they only exist once you insert data into them. Using use ensures all subsequent operations are
performed in this database.
2. Creating a Collection
[Link]("students")
Explanation:
Creates a collection named students. Collections are like tables in relational databases but schema-less,
meaning documents inside them can have different fields. Collections are also created automatically when
you insert a document.
3. Inserting Documents
Insert One Document
[Link]({ roll: 1, name: "Rahul", age: 21, course: "MCA" })
Explanation:
Adds a single document into the students collection. Each document is a JSON-like object with key-value
pairs.
Insert Many Documents
[Link]([
{ roll: 2, name: "Priya", age: 22, course: "Data Science" },
{ roll: 3, name: "Arjun", age: 23, course: "Cybersecurity" }
])
Explanation:
Adds multiple documents at once. Useful for bulk insertion when initializing a dataset.
4. Reading Documents
Find All Documents
[Link]().pretty()
Explanation:
Retrieves all documents from the students collection. The .pretty() method formats the output in a
readable way, showing each document clearly.
Find with Condition
[Link]({ age: { $gt: 21 } }).pretty()
Explanation:
Finds all students whose age is greater than 21. MongoDB supports comparison operators like $gt (greater
than), $lt (less than), $eq (equal).
5. Updating Documents
Update One Document
[Link]({ roll: 1 }, { $set: { course: "AI & ML" } })
Explanation:
Updates the course of the student with roll number 1. The $set operator modifies only the specified field
without affecting others.
Update Many Documents
[Link]({ course: "MCA" }, { $set: { year: 2 } })
Explanation:
Updates all students enrolled in MCA to year 2. updateMany applies changes to multiple documents at once.
Delete One Document
[Link]({ roll: 3 })
Explanation:
Deletes the first document that matches the condition (student with roll number 3).
Delete Many Documents
[Link]({ course: "Cybersecurity" })
Explanation:
Deletes all documents where the course is Cybersecurity.
7. Dropping a Collection
[Link]()
Explanation:
Removes the entire students collection along with all its documents. Use carefully, as this action cannot be
undone.
8. Aggregation Functions (Detailed Explanations)
Aggregation pipelines allow advanced data analysis. Each stage processes documents and passes results to
the next stage.
1. $group with $sum – Counting
[Link]([
{ $group: { _id: "$course", totalStudents: { $sum: 1 } } }
])
Explanation:
This groups documents by the course field. For each group, it counts the number of documents using $sum:
1. The _id field in $group represents the grouping key. The output shows each course with the total number
of students enrolled. This is useful for understanding distribution across categories.
2. $group with $avg – Average
[Link]([
{ $group: { _id: "$course", avgMarks: { $avg: "$marks" } } }
])
Explanation:
Groups students by course and calculates the average marks using $avg. Each group (course) will have one
result showing the mean of all marks. This is helpful for analyzing academic performance across different
courses.
3. $group with $min and $max – Minimum and Maximum
[Link]([
{ $group: { _id: "$course", minMarks: { $min: "$marks" }, maxMarks: { $max: "$marks"
} } }
])
Explanation:
Finds the lowest and highest marks in each course. $min returns the smallest value, $max returns the largest.
This helps identify top performers and weakest scores per course.
4. $match – Filtering
[Link]([
{ $match: { marks: { $gt: 85 } } }
])
Explanation:
Filters documents before further processing. Here, only students with marks greater than 85 are passed to the
next stage. $match works like a WHERE clause in SQL, narrowing down the dataset.
5. $sort – Sorting
[Link]([
{ $sort: { marks: -1 } }
])
Explanation:
Sorts documents based on the marks field. -1 means descending order, 1 means ascending. Sorting is often
combined with $limit to find top results, such as the highest scoring students.
6. $project – Selecting Fields
[Link]([
{ $project: { name: 1, course: 1, marks: 1 } }
])
Explanation:
Controls which fields are displayed in the output. Here, only name, course, and marks are shown. $project
is useful for creating clean reports without unnecessary fields.
7. $limit – Restricting Output
[Link]([
{ $limit: 5 }
])
Explanation:
Restricts the output to the first 5 documents. Often used with $sort to display top-N results, such as the top
5 students by marks.
8. $lookup – Joining Collections
[Link]([
{ $lookup: { from: "courses", localField: "course", foreignField: "cname", as:
"courseInfo" } }
])
Explanation:
Performs a join between two collections. Here, it matches the course field in students with the cname field
in courses. The joined data is stored in a new array field called courseInfo. This allows combining related
data across collections, similar to SQL joins.
Database: use
Collection: createCollection
Insert: insertOne, insertMany
Read: find().pretty(), findOne
Update: updateOne, updateMany
Delete: deleteOne, deleteMany
Drop: drop
Aggregation: $group, $sum, $avg, $min, $max, $match, $sort, $project, $limit, $lookup
MongoDB Lab Example
Question Scenario
A university wants to manage its academic resources using MongoDB. The administration has decided to
create a database named collegeDB to store information about different aspects of campus life. Within this
database, five collections should be created: students, courses, faculty, library, and hostel.
In the students collection, insert more than ten documents containing details such as roll number, name, age,
course, marks, and year of study. In each of the remaining collections, insert more than five documents with
appropriate fields (for example, courses should include course ID, name, duration, and credits; faculty
should include faculty ID, name, department, and years of experience; library should include book ID, title,
author, copies, and year of publication; hostel should include hostel ID, name, capacity, and warden).
After inserting the documents, display all records from each collection to verify the data. Perform at least
five update operations across different collections to modify existing information, such as updating student
marks, changing course durations, revising faculty departments, editing book titles, or adjusting hostel
capacities. Then, delete at least two documents from different collections to demonstrate removal
operations.
Finally, you must demonstrate four aggregate functions on the data:
1. Group students by course and count the number of students in each course.
2. Calculate the average marks of students per course.
3. Find the total number of copies of books grouped by author in the library.
4. Compute the overall capacity and average capacity of hostels.
Step 1: Use Database
use collegeDB
Explanation: Switches to (or creates) the database named collegeDB. All collections and documents will be
stored here.
Step 2: Create Collections
[Link]("students")
[Link]("courses")
[Link]("faculty")
[Link]("library")
[Link]("hostel")
Explanation: Creates five collections to store different categories of university data.
Step 3: Insert Documents
Students (more than 10 documents)
[Link]([
{ roll: 1, name: "Rahul", age: 21, course: "MCA", marks: 85, year: 1 },
{ roll: 2, name: "Priya", age: 22, course: "Data Science", marks: 90, year: 2 },
{ roll: 3, name: "Arjun", age: 23, course: "Cybersecurity", marks: 75, year: 2 },
{ roll: 4, name: "Sneha", age: 21, course: "MCA", marks: 88, year: 1 },
{ roll: 5, name: "Vikas", age: 24, course: "Data Science", marks: 92, year: 3 },
{ roll: 6, name: "Meera", age: 22, course: "AI & ML", marks: 81, year: 2 },
{ roll: 7, name: "Kiran", age: 23, course: "Cloud Computing", marks: 78, year: 2 },
{ roll: 8, name: "Anita", age: 21, course: "MCA", marks: 89, year: 1 },
{ roll: 9, name: "Ravi", age: 22, course: "Cybersecurity", marks: 83, year: 2 },
{ roll: 10, name: "Divya", age: 23, course: "Data Science", marks: 91, year: 3 },
{ roll: 11, name: "Sanjay", age: 24, course: "AI & ML", marks: 86, year: 3 }
])
Courses (more than 5 documents)
[Link]([
{ cid: 101, cname: "MCA", durationYears: 3, credits: 120 },
{ cid: 102, cname: "Data Science", durationYears: 2, credits: 80 },
{ cid: 103, cname: "Cybersecurity", durationYears: 2, credits: 80 },
{ cid: 104, cname: "AI & ML", durationYears: 2, credits: 80 },
{ cid: 105, cname: "Cloud Computing", durationYears: 2, credits: 80 },
{ cid: 106, cname: "Software Engineering", durationYears: 3, credits: 120 }
])
FACULTY INSERTION
[Link]([
{ fid: 1, name: "Dr. Sharma", dept: "MCA", experienceYears: 12 },
{ fid: 2, name: "Dr. Mehta", dept: "Data Science", experienceYears: 10 },
{ fid: 3, name: "Dr. Rao", dept: "Cybersecurity", experienceYears: 11 },
{ fid: 4, name: "Dr. Singh", dept: "AI & ML", experienceYears: 9 },
{ fid: 5, name: "Dr. Das", dept: "Cloud Computing", experienceYears: 8 },
{ fid: 6, name: "Dr. Iyer", dept: "Software Engineering", experienceYears: 13 }
])
lIBRARY INSERTION
[Link]([
{ bid: 1, title: "Database Systems", author: "Korth", copies: 5, year: 2018 },
{ bid: 2, title: "Artificial Intelligence", author: "Russell", copies: 4, year: 2020
},
{ bid: 3, title: "Network Security", author: "Anderson", copies: 6, year: 2017 },
{ bid: 4, title: "Cloud Architecture", author: "Miller", copies: 3, year: 2019 },
{ bid: 5, title: "Data Science Handbook", author: "Field", copies: 7, year: 2021 },
{ bid: 6, title: "Software Engineering", author: "Pressman", copies: 6, year: 2015 }
])
HOSTEL INSERTION
[Link]([
{ hid: 1, name: "A Block", capacity: 100, warden: "Mr. Kulkarni" },
{ hid: 2, name: "B Block", capacity: 120, warden: "Ms. Reddy" },
{ hid: 3, name: "C Block", capacity: 80, warden: "Mr. Kumar" },
{ hid: 4, name: "D Block", capacity: 150, warden: "Ms. Patel" },
{ hid: 5, name: "E Block", capacity: 90, warden: "Mr. Singh" },
{ hid: 6, name: "F Block", capacity: 110, warden: "Ms. Rao" }
])
Step 4: Display All Documents
[Link]().pretty()
[Link]().pretty()
[Link]().pretty()
[Link]().pretty()
[Link]().pretty()
Explanation: Lists all documents in each collection to verify insertion.
Step 5: Update Operations (5 examples)
[Link]({ roll: 1 }, { $set: { marks: 90 } })
[Link]({ cid: 102 }, { $set: { durationYears: 3 } })
[Link]({ fid: 2 }, { $set: { dept: "AI & ML" } })
[Link]({ bid: 2 }, { $set: { title: "AI Advanced Concepts" } })
[Link]({ hid: 1 }, { $set: { capacity: 110 } })
Explanation: Demonstrates updateOne and $set to modify specific fields in different collections.
Step 6: Delete Operations
[Link]({ roll: 3 })
[Link]({ copies: { $lt: 5 } })
Explanation: Removes one student record and deletes multiple books with fewer than 5 copies.
Step 7: Aggregation Functions (4 required)
1. Group students by course and count
[Link]([
{ $group: { _id: "$course", totalStudents: { $sum: 1 } } }
])
Explanation: Groups students by course and counts them using $sum.
2. Average marks per course
[Link]([
{ $group: { _id: "$course", avgMarks: { $avg: "$marks" } } }
])
Explanation: Calculates average marks of students in each course using $avg.
3. Total copies grouped by author
[Link]([
{ $group: { _id: "$author", totalCopies: { $sum: "$copies" } } }
])
Explanation: Groups books by author and sums up the number of copies.
4. Overall and average hostel capacity
[Link]([
{ $group: { _id: null, totalCapacity: { $sum: "$capacity" }, avgCapacity: { $avg:
"$capacity" } } }
])
Explanation: Computes total and average hostel capacity using $sum and $avg.