Skip to content

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)

  1. Scenario: Ek naya user Rahul database me add karna hai jiski age 25 hai.

    • Query: db.users.insertOne({ name: "Rahul", age: 25 })
  2. Scenario: Ek saath 3 products (Laptop, Mouse, Keyboard) products collection me daalne hain.

    • Query: db.products.insertMany([{name: "Laptop"}, {name: "Mouse"}, {name: "Keyboard"}])
  3. Scenario: Saare users ki list chahiye.

    • Query: db.users.find()
  4. Scenario: Sirf wo users chahiye jo “Delhi” se hain.

    • Query: db.users.find({ city: "Delhi" })
  5. Scenario: Pehle 5 users ko skip karke agle 5 users dekhne hain (Pagination).

    • Query: db.users.find().skip(5).limit(5)
  6. Scenario: “Rahul” naam ke user ki age update karke 26 karni hai.

    • Query: db.users.updateOne({ name: "Rahul" }, { $set: { age: 26 } })
  7. Scenario: Saare users jo “Mumbai” me rehte hain, unka status “Active” set karna hai.

    • Query: db.users.updateMany({ city: "Mumbai" }, { $set: { status: "Active" } })
  8. Scenario: Ek user ka record delete karna hai jiska email “test@example.com” hai.

    • Query: db.users.deleteOne({ email: "test@example.com" })
  9. Scenario: Saare inactive users ko remove karna hai.

    • Query: db.users.deleteMany({ status: "Inactive" })
  10. Scenario: Check karna hai ki total kitne products hain.

    • Query: db.products.countDocuments()
  11. Scenario: Sirf “Active” users ka count chahiye.

    • Query: db.users.countDocuments({ status: "Active" })
  12. Scenario: Ek user chahiye lekin output me sirf uska name aur email aana chahiye (_id nahi).

    • Query: db.users.findOne({}, { name: 1, email: 1, _id: 0 })
  13. Scenario: User ki age ko 1 saal se badhana hai (Increment).

    • Query: db.users.updateOne({ name: "Rahul" }, { $inc: { age: 1 } })
  14. Scenario: User ke profile se phone field ko hamesha ke liye hatana hai.

    • Query: db.users.updateOne({ name: "Rahul" }, { $unset: { phone: "" } })
  15. 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 })
  16. Scenario: Wo products chahiye jinka price 5000 hai.

    • Query: db.products.find({ price: 5000 })
  17. Scenario: Wo products chahiye jinka price 5000 NAHI hai.

    • Query: db.products.find({ price: { $ne: 5000 } })
  18. Scenario: Products ko price ke hisaab se Low-to-High sort karna hai.

    • Query: db.products.find().sort({ price: 1 })
  19. Scenario: Products ko price ke hisaab se High-to-Low sort karna hai.

    • Query: db.products.find().sort({ price: -1 })
  20. Scenario: Database me sabse pehla insert hua document chahiye.

    • Query: db.users.findOne()

Part 2: Operators & Complex Filtering (21-40)

  1. Scenario: Wo log chahiye jinki age 18 se zyada hai ($gt).

    • Query: db.users.find({ age: { $gt: 18 } })
  2. Scenario: Wo log chahiye jinki age 25 se kam ya barabar hai ($lte).

    • Query: db.users.find({ age: { $lte: 25 } })
  3. Scenario: Wo products chahiye jinka price 1000 se 5000 ke beech me hai.

    • Query: db.products.find({ price: { $gte: 1000, $lte: 5000 } })
  4. Scenario: Wo users chahiye jo “Delhi” YA “Mumbai” se hain ($in).

    • Query: db.users.find({ city: { $in: ["Delhi", "Mumbai"] } })
  5. Scenario: Wo users chahiye jo “Goa” ya “Pune” se NAHI hain ($nin).

    • Query: db.users.find({ city: { $nin: ["Goa", "Pune"] } })
  6. Scenario: Wo documents chahiye jisme phone field exist karta ho.

    • Query: db.users.find({ phone: { $exists: true } })
  7. Scenario: Wo documents chahiye jisme age field exist NAHI karta.

    • Query: db.users.find({ age: { $exists: false } })
  8. 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 } }] })
  9. 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 } }] })
  10. Scenario: Users jinka naam “A” se shuru hota hai (Regex).

    • Query: db.users.find({ name: /^A/ })
  11. Scenario: Users jinka naam “Singh” par khatam hota hai.

    • Query: db.users.find({ name: /Singh$/ })
  12. Scenario: Case-insensitive search karni hai “rahul” ke liye.

    • Query: db.users.find({ name: { $regex: "rahul", $options: "i" } })
  13. Scenario: Wo products chahiye jinke tags array me “Electronics” shamil hai.

    • Query: db.products.find({ tags: "Electronics" })
  14. Scenario: Wo products jinke tags bilkul exactly ["Electronics", "Apple"] hain (Order matters).

    • Query: db.products.find({ tags: ["Electronics", "Apple"] })
  15. Scenario: Wo products jinke tags me “Red” aur “Blue” dono hain (Order matter nahi karta) ($all).

    • Query: db.products.find({ tags: { $all: ["Red", "Blue"] } })
  16. Scenario: Wo users jinki hobbies array ka size 3 hai ($size).

    • Query: db.users.find({ hobbies: { $size: 3 } })
  17. Scenario: Ek user ke hobbies array me “Gaming” add karna hai ($push).

    • Query: db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: "Gaming" } })
  18. Scenario: Ek saath multiple hobbies add karni hain ($each).

    • Query: db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: { $each: ["Reading", "Swimming"] } } })
  19. Scenario: Hobbies array se “Gaming” hatana hai ($pull).

    • Query: db.users.updateOne({ name: "Rahul" }, { $pull: { hobbies: "Gaming" } })
  20. Scenario: Hobbies array ke last element ko remove karna hai ($pop).

    • Query: db.users.updateOne({ name: "Rahul" }, { $pop: { hobbies: 1 } })

Part 3: Deep Nesting & Arrays (41-60)

  1. Scenario: User ke address ke andar pincode find karna hai.

    • Query: db.users.find({ "address.pincode": 110001 })
  2. Scenario: Nested conditions: City Mumbai ho aur Street “MG Road” ho.

    • Query: db.users.find({ "address.city": "Mumbai", "address.street": "MG Road" })
  3. Scenario: Ek order me items array hai, wo order chahiye jisme kisi item ka price 5000 se zyada ho ($elemMatch ki zaroorat nahi agar single condition ho).

    • Query: db.orders.find({ "items.price": { $gt: 5000 } })
  4. 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 } } })
  5. Scenario: User ke first address ka city check karna hai (Array index).

    • Query: db.users.find({ "addresses.0.city": "Delhi" })
  6. Scenario: Address update karna jo nested object me hai.

    • Query: db.users.updateOne({ name: "Rahul" }, { $set: { "address.city": "Pune" } })
  7. 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 } })
  8. Scenario: Wo documents chahiye jahan scores array ka koi bhi number 80 se bada ho.

    • Query: db.students.find({ scores: { $gt: 80 } })
  9. Scenario: Wo documents jahan scores array ka koi element 80 se bada ho AUR 90 se chhota ho ($elemMatch).

    • Query: db.students.find({ scores: { $elemMatch: { $gt: 80, $lt: 90 } } })
  10. Scenario: Nested field specs.ram check karna hai.

    • Query: db.laptops.find({ "specs.ram": "16GB" })
  11. Scenario: User ke friends list me “Amit” hai ya nahi.

    • Query: db.users.find({ friends: "Amit" })
  12. Scenario: Kisi nested array ke andar naya object push karna.

    • Query: db.orders.updateOne({ _id: 1 }, { $push: { items: { name: "Keyboard", price: 1000 } } })
  13. Scenario: Nested array se specific object delete karna.

    • Query: db.orders.updateOne({ _id: 1 }, { $pull: { items: { name: "Mouse" } } })
  14. Scenario: Check karo ki address field null hai ya nahi.

    • Query: db.users.find({ address: null })
  15. Scenario: Wo user chahiye jiske paas exactly 2 addresses hain.

    • Query: db.users.find({ addresses: { $size: 2 } })
  16. Scenario: Key ka naam hi unknown ho to? (Wildcard Indexing scenario - conceptual).

    • Ans: db.collection.createIndex({ "$**": 1 })
  17. Scenario: Ek user document ke andar metadata.created_at field sort karna.

    • Query: db.users.find().sort({ "metadata.created_at": -1 })
  18. Scenario: 3 level deep nesting me query: a.b.c = 1.

    • Query: db.data.find({ "a.b.c": 1 })
  19. Scenario: Agar tags array exist karta hai aur null nahi hai.

    • Query: db.products.find({ tags: { $ne: null } })
  20. Scenario: Array ke second element ko match karna.

    • Query: db.products.find({ "tags.1": "Gaming" })

Part 4: Aggregation Framework (61-80)

  1. Scenario: Saare users ka total count (Aggregation se).

    • Query: db.users.aggregate([{ $count: "total" }])
  2. Scenario: City wise users count karne hain ($group).

    • Query: db.users.aggregate([{ $group: { _id: "$city", count: { $sum: 1 } } }])
  3. 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 } } }])
  4. Scenario: Average age nikalni hai saare users ki.

    • Query: db.users.aggregate([{ $group: { _id: null, avgAge: { $avg: "$age" } } }])
  5. Scenario: Sabse zyada age wala user dhoondhna hai ($max).

    • Query: db.users.aggregate([{ $group: { _id: null, maxAge: { $max: "$age" } } }])
  6. Scenario: Total sales calculate karni hai (Price sum).

    • Query: db.orders.aggregate([{ $group: { _id: null, totalRevenue: { $sum: "$totalAmount" } } }])
  7. 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" } } }])
  8. Scenario: Output me _id field nahi chahiye ($project).

    • Query: db.users.aggregate([{ $project: { _id: 0, name: 1, email: 1 } }])
  9. Scenario: Full name banana hai firstName aur lastName ko jod kar ($concat).

    • Query: db.users.aggregate([{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }])
  10. Scenario: Do collections orders aur users ko join karna hai ($lookup).

    • Query:
      db.orders.aggregate([
      {
      $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userDetails"
      }
      }
      ])
  11. Scenario: userDetails jo array banata hai, usse object banana hai ($unwind).

    • Query: db.orders.aggregate([{ $lookup: ... }, { $unwind: "$userDetails" }])
  12. Scenario: Top 5 expensive products nikalne hain aggregation se.

    • Query: db.products.aggregate([{ $sort: { price: -1 } }, { $limit: 5 }])
  13. 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" } } }])
  14. Scenario: Duplicate city values remove karke list chahiye ($addToSet).

    • Query: db.users.aggregate([{ $group: { _id: null, uniqueCities: { $addToSet: "$city" } } }])
  15. Scenario: Date se Year nikalna hai ($year).

    • Query: db.sales.aggregate([{ $project: { year: { $year: "$date" } } }])
  16. 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" }
      }
      }
      }
      ])
  17. Scenario: Null values ko replace karna ($ifNull).

    • Query: db.users.aggregate([{ $project: { name: 1,bio: { $ifNull: ["$bio", "No bio provided"] } } }])
  18. Scenario: Randomly 5 users pick karne hain ($sample).

    • Query: db.users.aggregate([{ $sample: { size: 5 } }])
  19. Scenario: Result ko alag collection me save karna hai ($out).

    • Query: db.users.aggregate([{ $match: { active: true } }, { $out: "active_users" }])
  20. 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 } }
      }
      }
      ])

Part 5: Indexing, Performance & Admin (81-100)

  1. Scenario: email field par query slow ho rahi hai. Kya karein?

    • Ans: Index banayein: db.users.createIndex({ email: 1 })
  2. Scenario: email duplicate nahi hona chahiye (Unique Index).

    • Ans: db.users.createIndex({ email: 1 }, { unique: true })
  3. Scenario: firstName aur lastName dono par ek sath search hoti hai (Compound Index).

    • Ans: db.users.createIndex({ firstName: 1, lastName: 1 })
  4. Scenario: Query ki performance check karni hai (Explain Plan).

    • Ans: db.users.find({ name: "Rahul" }).explain("executionStats")
  5. Scenario: Logs collection me documents apne aap 1 ghante baad delete ho jayein (TTL Index).

    • Ans: db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
  6. Scenario: Text search karni hai (Google jaisa search) purely keywords par.

    • Ans:
      1. Index: db.products.createIndex({ description: "text" })
      2. Query: db.products.find({ $text: { $search: "laptop" } })
  7. Scenario: Saare indexes dekhne hain.

    • Ans: db.users.getIndexes()
  8. Scenario: Ek unused index delete karna hai (dropIndex).

    • Ans: db.users.dropIndex("email_1")
  9. Scenario: Current database me kaunsi operations chal rahi hain?

    • Ans: db.currentOp()
  10. Scenario: Database stats check karne hain (Size, objects count).

    • Ans: db.stats()
  11. Scenario: Collection ko rename karna hai.

    • Ans: db.users.renameCollection("customers")
  12. Scenario: Database drop karna hai (Careful!).

    • Ans: db.dropDatabase()
  13. Scenario: Specific collection drop karna hai.

    • Ans: db.users.drop()
  14. Scenario: Slow queries log karni hain (Profiling).

    • Ans: db.setProfilingLevel(1, { slowms: 100 })
  15. Scenario: MapReduce ka alternative kya hai?

    • Ans: Aggregation Framework (Faster and easier).
  16. Scenario: Transaction use karni hai (ACID properties).

    • Ans: Session start karein -> session.startTransaction() -> Operations -> session.commitTransaction().
  17. Scenario: Backup lena hai database ka.

    • Ans: mongodump --db myDatabase --out /backup/path (Terminal command).
  18. Scenario: Backup restore karna hai.

    • Ans: mongorestore --db myDatabase /backup/path (Terminal command).
  19. Scenario: Data import karna hai JSON file se.

    • Ans: mongoimport --db test --collection users --file users.json
  20. Scenario: Data export karna hai CSV format me.

    • Ans: mongoexport --db test --collection users --type=csv --fields name,email --out users.csv

Pro tip: In 100 scenarios ko practice karke aap MongoDB ke master ban sakte hain! 🎓