100 MongoDB Practice Scenarios
Yahan 100 real-world scenarios hain jo aapko MongoDB expert banne me madad karenge. Har sawal ek practical problem par based hai.
Part 1: Basic CRUD Operations (1-20)
-
Scenario: Ek naya user
Rahuldatabase me add karna hai jiski age 25 hai.- Query:
db.users.insertOne({ name: "Rahul", age: 25 })
- Query:
-
Scenario: Ek saath 3 products (Laptop, Mouse, Keyboard) products collection me daalne hain.
- Query:
db.products.insertMany([{name: "Laptop"}, {name: "Mouse"}, {name: "Keyboard"}])
- Query:
-
Scenario: Saare users ki list chahiye.
- Query:
db.users.find()
- Query:
-
Scenario: Sirf wo users chahiye jo “Delhi” se hain.
- Query:
db.users.find({ city: "Delhi" })
- Query:
-
Scenario: Pehle 5 users ko skip karke agle 5 users dekhne hain (Pagination).
- Query:
db.users.find().skip(5).limit(5)
- Query:
-
Scenario: “Rahul” naam ke user ki age update karke 26 karni hai.
- Query:
db.users.updateOne({ name: "Rahul" }, { $set: { age: 26 } })
- Query:
-
Scenario: Saare users jo “Mumbai” me rehte hain, unka status “Active” set karna hai.
- Query:
db.users.updateMany({ city: "Mumbai" }, { $set: { status: "Active" } })
- Query:
-
Scenario: Ek user ka record delete karna hai jiska email “test@example.com” hai.
- Query:
db.users.deleteOne({ email: "test@example.com" })
- Query:
-
Scenario: Saare inactive users ko remove karna hai.
- Query:
db.users.deleteMany({ status: "Inactive" })
- Query:
-
Scenario: Check karna hai ki total kitne products hain.
- Query:
db.products.countDocuments()
- Query:
-
Scenario: Sirf “Active” users ka count chahiye.
- Query:
db.users.countDocuments({ status: "Active" })
- Query:
-
Scenario: Ek user chahiye lekin output me sirf uska
nameauremailaana chahiye (_idnahi).- Query:
db.users.findOne({}, { name: 1, email: 1, _id: 0 })
- Query:
-
Scenario: User ki age ko 1 saal se badhana hai (Increment).
- Query:
db.users.updateOne({ name: "Rahul" }, { $inc: { age: 1 } })
- Query:
-
Scenario: User ke profile se
phonefield ko hamesha ke liye hatana hai.- Query:
db.users.updateOne({ name: "Rahul" }, { $unset: { phone: "" } })
- Query:
-
Scenario: Agar user exist karta hai to update karo, nahi to naya bana do (Upsert).
- Query:
db.users.updateOne({ name: "Amit" }, { $set: { age: 30 } }, { upsert: true })
- Query:
-
Scenario: Wo products chahiye jinka price 5000 hai.
- Query:
db.products.find({ price: 5000 })
- Query:
-
Scenario: Wo products chahiye jinka price 5000 NAHI hai.
- Query:
db.products.find({ price: { $ne: 5000 } })
- Query:
-
Scenario: Products ko price ke hisaab se Low-to-High sort karna hai.
- Query:
db.products.find().sort({ price: 1 })
- Query:
-
Scenario: Products ko price ke hisaab se High-to-Low sort karna hai.
- Query:
db.products.find().sort({ price: -1 })
- Query:
-
Scenario: Database me sabse pehla insert hua document chahiye.
- Query:
db.users.findOne()
- Query:
Part 2: Operators & Complex Filtering (21-40)
-
Scenario: Wo log chahiye jinki age 18 se zyada hai (
$gt).- Query:
db.users.find({ age: { $gt: 18 } })
- Query:
-
Scenario: Wo log chahiye jinki age 25 se kam ya barabar hai (
$lte).- Query:
db.users.find({ age: { $lte: 25 } })
- Query:
-
Scenario: Wo products chahiye jinka price 1000 se 5000 ke beech me hai.
- Query:
db.products.find({ price: { $gte: 1000, $lte: 5000 } })
- Query:
-
Scenario: Wo users chahiye jo “Delhi” YA “Mumbai” se hain (
$in).- Query:
db.users.find({ city: { $in: ["Delhi", "Mumbai"] } })
- Query:
-
Scenario: Wo users chahiye jo “Goa” ya “Pune” se NAHI hain (
$nin).- Query:
db.users.find({ city: { $nin: ["Goa", "Pune"] } })
- Query:
-
Scenario: Wo documents chahiye jisme
phonefield exist karta ho.- Query:
db.users.find({ phone: { $exists: true } })
- Query:
-
Scenario: Wo documents chahiye jisme
agefield exist NAHI karta.- Query:
db.users.find({ age: { $exists: false } })
- Query:
-
Scenario: Wo users chahiye jo “Delhi” se hain AUR age 20 se zyada hai (
$and).- Query:
db.users.find({ $and: [{ city: "Delhi" }, { age: { $gt: 20 } }] })
- Query:
-
Scenario: Ya to user “Mumbai” se ho YA uski age 50 se zyada ho (
$or).- Query:
db.users.find({ $or: [{ city: "Mumbai" }, { age: { $gt: 50 } }] })
- Query:
-
Scenario: Users jinka naam “A” se shuru hota hai (Regex).
- Query:
db.users.find({ name: /^A/ })
- Query:
-
Scenario: Users jinka naam “Singh” par khatam hota hai.
- Query:
db.users.find({ name: /Singh$/ })
- Query:
-
Scenario: Case-insensitive search karni hai “rahul” ke liye.
- Query:
db.users.find({ name: { $regex: "rahul", $options: "i" } })
- Query:
-
Scenario: Wo products chahiye jinke tags array me “Electronics” shamil hai.
- Query:
db.products.find({ tags: "Electronics" })
- Query:
-
Scenario: Wo products jinke tags bilkul exactly
["Electronics", "Apple"]hain (Order matters).- Query:
db.products.find({ tags: ["Electronics", "Apple"] })
- Query:
-
Scenario: Wo products jinke tags me “Red” aur “Blue” dono hain (Order matter nahi karta) (
$all).- Query:
db.products.find({ tags: { $all: ["Red", "Blue"] } })
- Query:
-
Scenario: Wo users jinki hobbies array ka size 3 hai (
$size).- Query:
db.users.find({ hobbies: { $size: 3 } })
- Query:
-
Scenario: Ek user ke hobbies array me “Gaming” add karna hai (
$push).- Query:
db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: "Gaming" } })
- Query:
-
Scenario: Ek saath multiple hobbies add karni hain (
$each).- Query:
db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: { $each: ["Reading", "Swimming"] } } })
- Query:
-
Scenario: Hobbies array se “Gaming” hatana hai (
$pull).- Query:
db.users.updateOne({ name: "Rahul" }, { $pull: { hobbies: "Gaming" } })
- Query:
-
Scenario: Hobbies array ke last element ko remove karna hai (
$pop).- Query:
db.users.updateOne({ name: "Rahul" }, { $pop: { hobbies: 1 } })
- Query:
Part 3: Deep Nesting & Arrays (41-60)
-
Scenario: User ke address ke andar
pincodefind karna hai.- Query:
db.users.find({ "address.pincode": 110001 })
- Query:
-
Scenario: Nested conditions: City Mumbai ho aur Street “MG Road” ho.
- Query:
db.users.find({ "address.city": "Mumbai", "address.street": "MG Road" })
- Query:
-
Scenario: Ek order me items array hai, wo order chahiye jisme kisi item ka price 5000 se zyada ho (
$elemMatchki zaroorat nahi agar single condition ho).- Query:
db.orders.find({ "items.price": { $gt: 5000 } })
- Query:
-
Scenario: Array me specific object match karna: Item ka naam “Mouse” ho AUR price 500 ho (Dono same object me hone chahiye) - Important.
- Query:
db.orders.find({ items: { $elemMatch: { name: "Mouse", price: 500 } } })
- Query:
-
Scenario: User ke first address ka city check karna hai (Array index).
- Query:
db.users.find({ "addresses.0.city": "Delhi" })
- Query:
-
Scenario: Address update karna jo nested object me hai.
- Query:
db.users.updateOne({ name: "Rahul" }, { $set: { "address.city": "Pune" } })
- Query:
-
Scenario: Array of objects me se kisi specific item ka price update karna hai (Using
$).- Query:
db.orders.updateOne({ _id: 1, "items.name": "Mouse" }, { $set: { "items.$.price": 600 } })
- Query:
-
Scenario: Wo documents chahiye jahan
scoresarray ka koi bhi number 80 se bada ho.- Query:
db.students.find({ scores: { $gt: 80 } })
- Query:
-
Scenario: Wo documents jahan
scoresarray ka koi element 80 se bada ho AUR 90 se chhota ho ($elemMatch).- Query:
db.students.find({ scores: { $elemMatch: { $gt: 80, $lt: 90 } } })
- Query:
-
Scenario: Nested field
specs.ramcheck karna hai.- Query:
db.laptops.find({ "specs.ram": "16GB" })
- Query:
-
Scenario: User ke friends list me “Amit” hai ya nahi.
- Query:
db.users.find({ friends: "Amit" })
- Query:
-
Scenario: Kisi nested array ke andar naya object push karna.
- Query:
db.orders.updateOne({ _id: 1 }, { $push: { items: { name: "Keyboard", price: 1000 } } })
- Query:
-
Scenario: Nested array se specific object delete karna.
- Query:
db.orders.updateOne({ _id: 1 }, { $pull: { items: { name: "Mouse" } } })
- Query:
-
Scenario: Check karo ki
addressfieldnullhai ya nahi.- Query:
db.users.find({ address: null })
- Query:
-
Scenario: Wo user chahiye jiske paas exactly 2 addresses hain.
- Query:
db.users.find({ addresses: { $size: 2 } })
- Query:
-
Scenario: Key ka naam hi unknown ho to? (Wildcard Indexing scenario - conceptual).
- Ans:
db.collection.createIndex({ "$**": 1 })
- Ans:
-
Scenario: Ek user document ke andar
metadata.created_atfield sort karna.- Query:
db.users.find().sort({ "metadata.created_at": -1 })
- Query:
-
Scenario: 3 level deep nesting me query:
a.b.c = 1.- Query:
db.data.find({ "a.b.c": 1 })
- Query:
-
Scenario: Agar
tagsarray exist karta hai aur null nahi hai.- Query:
db.products.find({ tags: { $ne: null } })
- Query:
-
Scenario: Array ke second element ko match karna.
- Query:
db.products.find({ "tags.1": "Gaming" })
- Query:
Part 4: Aggregation Framework (61-80)
-
Scenario: Saare users ka total count (Aggregation se).
- Query:
db.users.aggregate([{ $count: "total" }])
- Query:
-
Scenario: City wise users count karne hain (
$group).- Query:
db.users.aggregate([{ $group: { _id: "$city", count: { $sum: 1 } } }])
- Query:
-
Scenario: Sirf “Active” users ko city wise group karna hai (
$match+$group).- Query:
db.users.aggregate([{ $match: { status: "Active" } }, { $group: { _id: "$city", count: { $sum: 1 } } }])
- Query:
-
Scenario: Average age nikalni hai saare users ki.
- Query:
db.users.aggregate([{ $group: { _id: null, avgAge: { $avg: "$age" } } }])
- Query:
-
Scenario: Sabse zyada age wala user dhoondhna hai (
$max).- Query:
db.users.aggregate([{ $group: { _id: null, maxAge: { $max: "$age" } } }])
- Query:
-
Scenario: Total sales calculate karni hai (Price sum).
- Query:
db.orders.aggregate([{ $group: { _id: null, totalRevenue: { $sum: "$totalAmount" } } }])
- Query:
-
Scenario: Users ko city ke hisaab se group karo aur har city ke users ke naam ki list banao (
$push).- Query:
db.users.aggregate([{ $group: { _id: "$city", users: { $push: "$name" } } }])
- Query:
-
Scenario: Output me
_idfield nahi chahiye ($project).- Query:
db.users.aggregate([{ $project: { _id: 0, name: 1, email: 1 } }])
- Query:
-
Scenario: Full name banana hai
firstNameaurlastNameko jod kar ($concat).- Query:
db.users.aggregate([{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }])
- Query:
-
Scenario: Do collections
ordersaurusersko join karna hai ($lookup).- Query:
db.orders.aggregate([{$lookup: {from: "users",localField: "userId",foreignField: "_id",as: "userDetails"}}])
- Query:
-
Scenario:
userDetailsjo array banata hai, usse object banana hai ($unwind).- Query:
db.orders.aggregate([{ $lookup: ... }, { $unwind: "$userDetails" }])
- Query:
-
Scenario: Top 5 expensive products nikalne hain aggregation se.
- Query:
db.products.aggregate([{ $sort: { price: -1 } }, { $limit: 5 }])
- Query:
-
Scenario: Check karna hai ki kitne users ki age 30 se zyada hai aur unka total balance kya hai.
- Query:
db.users.aggregate([{ $match: { age: { $gt: 30 } } }, { $group: { _id: null, totalBalance: { $sum: "$balance" } } }])
- Query:
-
Scenario: Duplicate city values remove karke list chahiye (
$addToSet).- Query:
db.users.aggregate([{ $group: { _id: null, uniqueCities: { $addToSet: "$city" } } }])
- Query:
-
Scenario: Date se Year nikalna hai (
$year).- Query:
db.sales.aggregate([{ $project: { year: { $year: "$date" } } }])
- Query:
-
Scenario: Conditional Output: Agar price 1000 se zyada hai to “Expensive”, nahi to “Cheap” (
$cond).- Query:
db.products.aggregate([{$project: {category: {$cond: { if: { $gt: ["$price", 1000] }, then: "Expensive", else: "Cheap" }}}}])
- Query:
-
Scenario: Null values ko replace karna (
$ifNull).- Query:
db.users.aggregate([{ $project: { name: 1,bio: { $ifNull: ["$bio", "No bio provided"] } } }])
- Query:
-
Scenario: Randomly 5 users pick karne hain (
$sample).- Query:
db.users.aggregate([{ $sample: { size: 5 } }])
- Query:
-
Scenario: Result ko alag collection me save karna hai (
$out).- Query:
db.users.aggregate([{ $match: { active: true } }, { $out: "active_users" }])
- Query:
-
Scenario: Bucket categorization (Age 0-18, 19-30, etc.) (
$bucket).- Query:
db.users.aggregate([{$bucket: {groupBy: "$age",boundaries: [0, 18, 30, 50, 100],default: "Other",output: { count: { $sum: 1 } }}}])
- Query:
Part 5: Indexing, Performance & Admin (81-100)
-
Scenario:
emailfield par query slow ho rahi hai. Kya karein?- Ans: Index banayein:
db.users.createIndex({ email: 1 })
- Ans: Index banayein:
-
Scenario:
emailduplicate nahi hona chahiye (Unique Index).- Ans:
db.users.createIndex({ email: 1 }, { unique: true })
- Ans:
-
Scenario:
firstNameaurlastNamedono par ek sath search hoti hai (Compound Index).- Ans:
db.users.createIndex({ firstName: 1, lastName: 1 })
- Ans:
-
Scenario: Query ki performance check karni hai (Explain Plan).
- Ans:
db.users.find({ name: "Rahul" }).explain("executionStats")
- Ans:
-
Scenario: Logs collection me documents apne aap 1 ghante baad delete ho jayein (TTL Index).
- Ans:
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
- Ans:
-
Scenario: Text search karni hai (Google jaisa search) purely keywords par.
- Ans:
- Index:
db.products.createIndex({ description: "text" }) - Query:
db.products.find({ $text: { $search: "laptop" } })
- Index:
- Ans:
-
Scenario: Saare indexes dekhne hain.
- Ans:
db.users.getIndexes()
- Ans:
-
Scenario: Ek unused index delete karna hai (
dropIndex).- Ans:
db.users.dropIndex("email_1")
- Ans:
-
Scenario: Current database me kaunsi operations chal rahi hain?
- Ans:
db.currentOp()
- Ans:
-
Scenario: Database stats check karne hain (Size, objects count).
- Ans:
db.stats()
- Ans:
-
Scenario: Collection ko rename karna hai.
- Ans:
db.users.renameCollection("customers")
- Ans:
-
Scenario: Database drop karna hai (Careful!).
- Ans:
db.dropDatabase()
- Ans:
-
Scenario: Specific collection drop karna hai.
- Ans:
db.users.drop()
- Ans:
-
Scenario: Slow queries log karni hain (Profiling).
- Ans:
db.setProfilingLevel(1, { slowms: 100 })
- Ans:
-
Scenario: MapReduce ka alternative kya hai?
- Ans: Aggregation Framework (Faster and easier).
-
Scenario: Transaction use karni hai (ACID properties).
- Ans: Session start karein ->
session.startTransaction()-> Operations ->session.commitTransaction().
- Ans: Session start karein ->
-
Scenario: Backup lena hai database ka.
- Ans:
mongodump --db myDatabase --out /backup/path(Terminal command).
- Ans:
-
Scenario: Backup restore karna hai.
- Ans:
mongorestore --db myDatabase /backup/path(Terminal command).
- Ans:
-
Scenario: Data import karna hai JSON file se.
- Ans:
mongoimport --db test --collection users --file users.json
- Ans:
-
Scenario: Data export karna hai CSV format me.
- Ans:
mongoexport --db test --collection users --type=csv --fields name,email --out users.csv
- Ans: