Introduction
Advanced MongoDB practice problems help you move beyond basic find(), insertOne(), and updateOne() operations. In this chapter, you will solve practical problems involving nested documents, arrays, aggregation, conditional updates, grouping, sorting, lookups, and indexes. These questions are designed to improve your problem-solving skills and show how MongoDB features can be combined to handle data commonly found in real applications. Advanced MongoDB Practice Problems with Solutions to help you understand the concepts.
Q1. Find Students Who Have Multiple Required Skills
Problem Statement
Find students who have both Python and MongoDB in their skills array.
MongoDB Query
db.students.find({
skills: {
$all: ["Python", "MongoDB"]
}
})
Expected Output
[
{
name: "Rahul",
skills: ["Python", "MongoDB", "SQL"]
},
{
name: "Neha",
skills: ["Python", "MongoDB", "JavaScript"]
}
]
Explanation
The $all operator checks whether an array contains all specified values.
This is useful when you need students who have several required skills at the same time.
Q2. Find Students Using Conditions on the Same Array Element
Problem Statement
Suppose each student has an array of course results:
{
name: "Rahul",
results: [
{ subject: "Python", marks: 85 },
{ subject: "SQL", marks: 72 }
]
}
Find students who scored more than 80 marks in Python.
MongoDB Query
db.students.find({
results: {
$elemMatch: {
subject: "Python",
marks: { $gt: 80 }
}
}
})
Expected Output
[
{
name: "Rahul",
results: [
{ subject: "Python", marks: 85 },
{ subject: "SQL", marks: 72 }
]
}
]
Explanation
$elemMatch is important when multiple conditions must apply to the same array element.
Here, both conditions must belong to the same result:
subject = Python
marks > 80
Q3. Find Employees Whose Salary Is Above the Department Average
Problem Statement
An employees collection contains:
{
name: "Aman",
department: "IT",
salary: 60000
}
Find employees whose salary is greater than the average salary of all employees.
MongoDB Query
db.employees.aggregate([
{
$group: {
_id: null,
averageSalary: { $avg: "$salary" }
}
},
{
$lookup: {
from: "employees",
pipeline: [],
as: "employees"
}
},
{
$unwind: "$employees"
},
{
$match: {
$expr: {
$gt: [
"$employees.salary",
"$averageSalary"
]
}
}
},
{
$project: {
_id: 0,
name: "$employees.name",
department: "$employees.department",
salary: "$employees.salary",
averageSalary: 1
}
}
])
Expected Output
[
{
name: "Aman",
department: "IT",
salary: 70000,
averageSalary: 57500
},
{
name: "Priya",
department: "HR",
salary: 65000,
averageSalary: 57500
}
]
Explanation
The aggregation pipeline first calculates the average salary.
Then $lookup brings the employee documents into the pipeline so their salaries can be compared with that average.
$expr allows MongoDB to compare two field/expression values.
Q4. Calculate Total Order Amount for Each Customer
Problem Statement
An orders collection contains:
{
customerId: 101,
amount: 5000
}
Calculate the total order amount for every customer.
MongoDB Query
db.orders.aggregate([
{
$group: {
_id: "$customerId",
totalAmount: {
$sum: "$amount"
}
}
},
{
$sort: {
totalAmount: -1
}
}
])
Expected Output
[
{
_id: 101,
totalAmount: 15000
},
{
_id: 102,
totalAmount: 12000
},
{
_id: 103,
totalAmount: 8000
}
]
Explanation
$group groups orders by customerId.
$sum calculates the total amount for each customer.
Finally, $sort displays customers with the highest total amount first.
Q5. Find the Top 3 Highest-Paid Employees
Problem Statement
Find the three employees with the highest salaries.
MongoDB Query
db.employees.find(
{},
{
_id: 0,
name: 1,
department: 1,
salary: 1
}
)
.sort({
salary: -1
})
.limit(3)
Expected Output
[
{
name: "Aman",
department: "IT",
salary: 90000
},
{
name: "Priya",
department: "HR",
salary: 85000
},
{
name: "Rahul",
department: "Finance",
salary: 80000
}
]
Explanation
The query:
.sort({ salary: -1 })
sorts salaries from highest to lowest.
Then:
.limit(3)
returns only the first three employees.
Q6. Increase Salaries for Employees in a Department
Problem Statement
Increase the salary of every employee in the IT department by 10%.
MongoDB Query
db.employees.updateMany(
{
department: "IT"
},
[
{
$set: {
salary: {
$multiply: ["$salary", 1.10]
}
}
}
]
)
Expected Output
{
matchedCount: 3,
modifiedCount: 3
}
For example:
Before:
salary: 50000
After:
salary: 55000
Explanation
This example uses an update pipeline.
$multiply calculates:
salary × 1.10
So a salary of 50000 becomes:
55000
This is different from a simple $inc because the increase is calculated as a percentage of the existing value.
Q7. Find Products Whose Average Rating Is Greater Than 4
Problem Statement
A products collection contains a reviews array:
{
name: "Laptop",
reviews: [
{ rating: 5 },
{ rating: 4 },
{ rating: 5 }
]
}
Find products whose average review rating is greater than 4.
MongoDB Query
db.products.aggregate([
{
$unwind: "$reviews"
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
averageRating: {
$avg: "$reviews.rating"
}
}
},
{
$match: {
averageRating: { $gt: 4 }
}
}
])
Expected Output
[
{
_id: ObjectId("..."),
name: "Laptop",
averageRating: 4.67
}
]
Explanation
$unwind creates a separate pipeline document for each review.
$avg calculates the average rating.
$match keeps only products whose average rating is greater than 4.
Q8. Join Customers with Their Orders
Problem Statement
A customers collection contains customer information and an orders collection stores orders using customerId.
Use $lookup to display each customer together with their orders.
MongoDB Query
db.customers.aggregate([
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "customerId",
as: "orders"
}
}
])
Expected Output
[
{
_id: ObjectId("..."),
name: "Rahul",
city: "Delhi",
orders: [
{
customerId: ObjectId("..."),
amount: 5000
},
{
customerId: ObjectId("..."),
amount: 7000
}
]
}
]
Explanation
$lookup performs a join-like operation between two collections.
Here:
customers._id
↓
orders.customerId
Matching orders are placed inside the orders array.
Q9. Find Duplicate Email Addresses
Problem Statement
Find email addresses that occur more than once in the users collection.
MongoDB Query
db.users.aggregate([
{
$group: {
_id: "$email",
count: {
$sum: 1
}
}
},
{
$match: {
count: { $gt: 1 }
}
}
])
Expected Output
[
{
_id: "rahul@example.com",
count: 2
},
{
_id: "neha@example.com",
count: 3
}
]
Explanation
$group groups documents by email address.
The expression:
{ $sum: 1 }
counts how many documents belong to each email.
Then:
{ count: { $gt: 1 } }
keeps only duplicate emails.
This is a useful technique for detecting data-quality problems.
Q10. Analyze a Slow Query and Create an Index
Problem Statement
An application frequently searches employees using:
{
department: "IT",
salary: { $gt: 60000 }
}
Create an appropriate compound index and use explain() to inspect the query.
MongoDB Query
First create the index:
db.employees.createIndex({
department: 1,
salary: 1
})
Then analyze the query:
db.employees.find({
department: "IT",
salary: { $gt: 60000 }
}).explain("executionStats")
Expected Output
The exact output depends on your MongoDB version, data, and indexes. You may see information similar to:
{
executionStats: {
nReturned: 5,
totalKeysExamined: 5,
totalDocsExamined: 5
}
}
The query plan may include:
IXSCAN
Explanation
The compound index:
{
department: 1,
salary: 1
}
supports queries that use department and salary in this pattern.
explain("executionStats") helps inspect how MongoDB executed the query.
Do not assume that an index is automatically faster in every situation. The actual benefit depends on the collection size, query pattern, data distribution, and other indexes.
Key Takeaways
- Advanced MongoDB problems often require combining multiple MongoDB features.
$allis useful when multiple values must exist in an array.$elemMatchis useful when multiple conditions must apply to the same array element.- Aggregation pipelines can perform calculations, grouping, filtering, sorting, and transformations.
$groupcan calculate totals, averages, and counts.$sumcan calculate totals or counts.$avgcan calculate average values.$unwindis useful for processing individual elements of an array.$lookupcan combine related documents from different collections.- Update pipelines can calculate new field values during updates.
$multiplycan be used for percentage-based calculations.- Aggregation can help identify duplicate data.
- Compound indexes can improve frequently used multi-field queries.
explain("executionStats")helps analyze query execution.- Advanced MongoDB development is about combining features to solve real data problems.
FAQs
1. What are advanced MongoDB practice problems?
Advanced MongoDB practice problems require combining MongoDB features such as aggregation, nested queries, array operators, update pipelines, $lookup, and indexes to solve practical data problems.
2. Why is $elemMatch important in advanced MongoDB queries?
$elemMatch is useful when multiple conditions need to match the same element inside an array, especially an array of embedded documents.
3. How is $lookup used in advanced MongoDB applications?
$lookup combines related documents from another collection. It is commonly used when an application stores related information using references.
4. Can MongoDB calculate averages and totals?
Yes. MongoDB’s aggregation framework provides operators such as $avg and $sum for calculating averages, totals, and counts.
5. What is an update pipeline in MongoDB?
An update pipeline allows MongoDB to use aggregation-style stages during an update. It is useful when the new field value needs to be calculated from existing document values.
6. How can MongoDB find duplicate records?
MongoDB can use $group with $sum to count documents having the same value and then use $match to find groups with a count greater than one.
7. Why should explain() be used for advanced MongoDB queries?
explain("executionStats") provides information about how MongoDB executed a query, including statistics such as documents examined, index keys examined, and returned documents. It helps developers investigate query performance.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
