There are several common concepts which are repeated in interviews from beginners to advanced interviews. Depending on the requirements the questions asked may vary; If working with the large data you might face questions on Sharding, Replication and Managing cluster along with indexing and improving Db queries. Different questions of search applications, transactions and more. The common area is Aggregation. I am covering the basic ones.
We will start with concepts which could be asked in the interview
Frequency
Q. Determine the most frequently occurring city in a collection of customer addresses.
A. We will group the documents by city names and count their occurrences and sort the count by descending order and only show the first one which is highest occuring
db.customers.aggregate([
{ $group: {
_id: "$city",
count: { $sum: 1 }
}},
{ $sort: { count: -1 } },
{ $limit: 1 }
])
Conditional Group
Q. Calculate the total sales for each product category, but only include products with a price over $50 and a quantity in stock greater than 10.
A. Total Sales = Quantity of Product Sold x its Price
We will find the products which matches the condition and then will group by its category
db.products.aggregate([
{ $match: { price: { $gt: 50 }, quantity: { $gt: 10 } } },
{ $group: {
_id: "$productCategory",
totalSales: { $sum: { $multiply: ["$price", "$quantity"] } }
}}
])
Moving Average
Q Calculate a 3-day moving average of stock prices. Assume each document has a date and price field.
A First we will sort documents date wise, then push the price of the stock in array and take the average of the last 3 values of the array
db.stockData.aggregate([
{
$sort: { $date: 1 } //ASC
},
{
$group: {
_id: null,
priceArray: {$push: "$stockPrice"}
}
},
{
$project: {
threeDayAvg: {
$avg: {
$slice: ["$priceArray", -3] // -3 to get last 3 values
}
}
}
}
])
Other questions consist of the text search with $regex
db.users.find([
$or: [
{ $firstName: {$regex: searchedString }},
{ $lastName: {$regex: searchedString }}
]
])
One with using Bucket
Q. Group the Students by the total marks range above 70 and count the number of students
db.students.aggregate([
{
$bucket: {
$groupBy: 'totalMarks',
boundaries: [70, 80, 90, 100],
default: "Other", // We dont want to through error if the student doesnot fall in the marks rage
output: {
count: { $sun: 1 }
}
}
}
])
Q. Given a collection of blog posts with tags nested inside an array, find the tags with maximum occurrences.
db.blogs.aggreagate([
{ $unwind: "$tags" },
{ $sort: -1 },
{ $limit: 1 }
])
Suggest MongoDB aggregation pipeline questions for medium and advance level and we will solve it together. Till then Happy Coding 🚀👨💻
Ping me on
LinkedIn: Shrey Banugaria
Top comments (0)