Section 11: Projects

πŸ› Query Debugging Practice

Find and Fix 50 Broken MongoDB Queries - Master Debugging!s

πŸŽ“ About Debugging Practice

Debugging broken queries is a critical real-world skill. These 50 questions will sharpen your MongoDB debugging abilities through hands-on practice.

πŸ› Bug Categories:
  • Syntax Errors (1-10): Missing brackets, wrong quotes, incorrect operators
  • Logic Errors (11-20): Query runs but returns wrong results
  • Operator Misuse (21-30): Using wrong operator for the task
  • Aggregation Bugs (31-40): Pipeline mistakes and stage order issues
  • Update Errors (41-50): Wrong update syntax and operator usage
πŸ’‘ How to Practice:
  • Read carefully: Study the data and intended goal
  • Spot the bug: Identify what's wrong with the query
  • Fix mentally: Think about the correct syntax/logic
  • Check solution: Compare your fix with the answer
  • Understand why: Read the explanation to prevent future errors

Your Progress

0
Debugged
50
Total Bugs
0%

⚠️ Syntax Errors (1-10)

These queries have syntax problems that prevent them from running.

Bug #1 Easy Syntax Error

Collection: students

[{_id:1,name:'Alice',grade:'A'},{_id:2,name:'Bob',grade:'B'}]

🎯 Goal:

Find students with grade A

❌ Broken Query:

This query has a bug!
db.students.find({grade:'A'})
Error: Invalid token
πŸ’‘ Hint:

Check quote marks

βœ“ Correct Query:

Fixed Version
db.students.find({grade:"A"})
πŸ“– What Was Wrong:

Use double quotes for strings in MongoDB

Bug #2 Easy Syntax Error

Collection: products

[{_id:1,name:'Laptop',price:1200},{_id:2,name:'Mouse',price:25}]

🎯 Goal:

Find products price > 50

❌ Broken Query:

This query has a bug!
db.products.find({price:{$gt 50}})
Error: Unexpected number
πŸ’‘ Hint:

Check operator syntax

βœ“ Correct Query:

Fixed Version
db.products.find({price:{$gt:50}})
πŸ“– What Was Wrong:

Missing colon after $gt operator

Bug #3 Easy Syntax Error

Collection: orders

[{_id:1,customer:'Alice',total:150}]

🎯 Goal:

Find orders for Alice with projection

❌ Broken Query:

This query has a bug!
db.orders.find({customer:"Alice"},{customer:1,total:1,_id:0}
Error: missing )
πŸ’‘ Hint:

Count parentheses

βœ“ Correct Query:

Fixed Version
db.orders.find({customer:"Alice"},{customer:1,total:1,_id:0})
πŸ“– What Was Wrong:

Missing closing parenthesis

Bug #4 Medium Syntax Error

Collection: employees

[{name:'John',dept:'IT',salary:80000}]

🎯 Goal:

Find IT employees, sort by salary desc

❌ Broken Query:

This query has a bug!
db.employees.find({dept:"IT"}).sort{salary:-1}
Error: Unexpected {
πŸ’‘ Hint:

Check method chaining

βœ“ Correct Query:

Fixed Version
db.employees.find({dept:"IT"}).sort({salary:-1})
πŸ“– What Was Wrong:

Missing parentheses around sort()

Bug #5 Easy Syntax Error

Collection: books

[{title:'MongoDB',pages:320},{title:'Node',pages:280}]

🎯 Goal:

Find books 300-400 pages

❌ Broken Query:

This query has a bug!
db.books.find({pages:{$gte:300,$lte 400}})
Error: Unexpected number
πŸ’‘ Hint:

Compare $gte vs $lte syntax

βœ“ Correct Query:

Fixed Version
db.books.find({pages:{$gte:300,$lte:400}})
πŸ“– What Was Wrong:

Missing colon after $lte

Bug #6 Easy Syntax Error

Collection: users

[{username:'alice',status:'active'}]

🎯 Goal:

Find active users

❌ Broken Query:

This query has a bug!
db.users.find({status:"active")
Error: missing }
πŸ’‘ Hint:

Check curly braces

βœ“ Correct Query:

Fixed Version
db.users.find({status:"active"})
πŸ“– What Was Wrong:

Missing closing brace

Bug #7 Medium Syntax Error

Collection: inventory

[{item:'apple',qty:50,price:2.5}]

🎯 Goal:

Find qty>20 AND price<3

❌ Broken Query:

This query has a bug!
db.inventory.find({qty:{$gt:20}price:{$lt:3}})
Error: Unexpected identifier
πŸ’‘ Hint:

What separates conditions?

βœ“ Correct Query:

Fixed Version
db.inventory.find({qty:{$gt:20},price:{$lt:3}})
πŸ“– What Was Wrong:

Missing comma between conditions

Bug #8 Easy Syntax Error

Collection: posts

[{title:'Hello',likes:10}]

🎯 Goal:

Update likes to 30

❌ Broken Query:

This query has a bug!
db.posts.updateOne({_id:1},{set:{likes:30}})
Error: No update
πŸ’‘ Hint:

Check operator name

βœ“ Correct Query:

Fixed Version
db.posts.updateOne({_id:1},{$set:{likes:30}})
πŸ“– What Was Wrong:

Missing $ before set

Bug #9 Medium Syntax Error

Collection: tasks

[{name:'A',tags:['urgent','work']}]

🎯 Goal:

Find tasks with urgent tag

❌ Broken Query:

This query has a bug!
db.tasks.find({tags:"urgent")
Error: missing }
πŸ’‘ Hint:

Match braces

βœ“ Correct Query:

Fixed Version
db.tasks.find({tags:"urgent"})
πŸ“– What Was Wrong:

Missing closing brace

Bug #10 Hard Syntax Error

Collection: sales

[{product:'A',amount:100}]

🎯 Goal:

Find amount 100 OR 200

❌ Broken Query:

This query has a bug!
db.sales.find({amount:{$or:[100,200]}})
Error: Returns nothing
πŸ’‘ Hint:

$or placement

βœ“ Correct Query:

Fixed Version
db.sales.find({$or:[{amount:100},{amount:200}]})
πŸ“– What Was Wrong:

$or is top-level, not inside field. Or use {amount:{$in:[100,200]}}

🧩 Logic Errors (11-20)

These queries run without errors but return incorrect results.

Bug #11 Medium Logic Error

Collection: products

[{name:'Laptop',price:1200,inStock:true},{name:'Mouse',price:25,inStock:false}]

🎯 Goal:

Find inStock OR price<100

❌ Broken Query:

This query has a bug!
db.products.find({inStock:true,price:{$lt:100}})
Error: Wrong results
πŸ’‘ Hint:

Multiple conditions use AND

βœ“ Correct Query:

Fixed Version
db.products.find({$or:[{inStock:true},{price:{$lt:100}}]})
πŸ“– What Was Wrong:

Use $or for OR logic

Bug #12 Medium Logic Error

Collection: students

[{name:'Alice',scores:[85,90,88]}]

🎯 Goal:

Find students with score 90

❌ Broken Query:

This query has a bug!
db.students.find({scores:90})
Error: Works but implicit
πŸ’‘ Hint:

Be more explicit

βœ“ Correct Query:

Fixed Version
db.students.find({scores:{$eq:90}})
πŸ“– What Was Wrong:

Use $eq or $in for clarity

Bug #13 Hard Logic Error

Collection: orders

[{customer:'Alice',total:150},{customer:'Bob',total:50},{customer:'Charlie',total:200}]

🎯 Goal:

Find top 2 by total

❌ Broken Query:

This query has a bug!
db.orders.find().limit(2).sort({total:-1})
Error: Wrong order
πŸ’‘ Hint:

Sort before limit!

βœ“ Correct Query:

Fixed Version
db.orders.find().sort({total:-1}).limit(2)
πŸ“– What Was Wrong:

CRITICAL: sort() before limit()

Bug #14 Medium Logic Error

Collection: users

[{age:25,city:'NYC'},{age:30,city:'LA'}]

🎯 Goal:

Find age 25 in LA

❌ Broken Query:

This query has a bug!
db.users.find({age:25}).find({city:"LA"})
Error: Cannot chain find
πŸ’‘ Hint:

One find() call

βœ“ Correct Query:

Fixed Version
db.users.find({age:25,city:"LA"})
πŸ“– What Was Wrong:

Multiple conditions in one find()

Bug #15 Medium Logic Error

Collection: items

[{qty:5,tags:['a','b']},{qty:10,tags:['b','c']}]

🎯 Goal:

Find qty>=5 AND tag b

❌ Broken Query:

This query has a bug!
db.items.find({qty:{$gte:5},tags:["b"]})
Error: Returns nothing
πŸ’‘ Hint:

Array equality vs contains

βœ“ Correct Query:

Fixed Version
db.items.find({qty:{$gte:5},tags:"b"})
πŸ“– What Was Wrong:

tags:["b"] checks equality, tags:"b" checks contains

Bug #16 Hard Logic Error

Collection: employees

[{name:'John',dept:'IT'},{name:'Sarah',dept:'HR'}]

🎯 Goal:

Find NOT in IT

❌ Broken Query:

This query has a bug!
db.employees.find({dept:{$not:"IT"}})
Error: $not needs regex
πŸ’‘ Hint:

$not vs $ne

βœ“ Correct Query:

Fixed Version
db.employees.find({dept:{$ne:"IT"}})
πŸ“– What Was Wrong:

Use $ne for not equal

Bug #17 Medium Logic Error

Collection: posts

[{views:100,likes:20},{views:50,likes:30}]

🎯 Goal:

Find views>75 OR likes>25

❌ Broken Query:

This query has a bug!
db.posts.find({views:{$gt:75},likes:{$gt:25}})
Error: Returns only 1
πŸ’‘ Hint:

AND vs OR

βœ“ Correct Query:

Fixed Version
db.posts.find({$or:[{views:{$gt:75}},{likes:{$gt:25}}]})
πŸ“– What Was Wrong:

Comma = AND, use $or

Bug #18 Easy Logic Error

Collection: records

[{score:'95'},{score:85}]

🎯 Goal:

Find score>90

❌ Broken Query:

This query has a bug!
db.records.find({score:{$gt:90}})
Error: Misses string
πŸ’‘ Hint:

Check data types

βœ“ Correct Query:

Fixed Version
db.records.find({score:{$gt:"90"}})
πŸ“– What Was Wrong:

Match types: "95" vs 95

Bug #19 Hard Logic Error

Collection: accounts

[{balance:100},{balance:200}]

🎯 Goal:

Get average balance

❌ Broken Query:

This query has a bug!
db.accounts.find({}).avg("balance")
Error: Not a function
πŸ’‘ Hint:

Use aggregation

βœ“ Correct Query:

Fixed Version
db.accounts.aggregate([{$group:{_id:null,avg:{$avg:"$balance"}}}])
πŸ“– What Was Wrong:

Use $avg in aggregation

Bug #20 Medium Logic Error

Collection: inventory

[{item:'A',qty:[5,10,15]}]

🎯 Goal:

Find ANY qty>12

❌ Broken Query:

This query has a bug!
db.inventory.find({qty:{$gt:12}})
Error: Works but implicit
πŸ’‘ Hint:

Be explicit for arrays

βœ“ Correct Query:

Fixed Version
db.inventory.find({qty:{$elemMatch:{$gt:12}}})
πŸ“– What Was Wrong:

Use $elemMatch for clarity

πŸ”§ Operator Mistakes (21-30)

Using the wrong operator for the task.

Bug #21 Medium Wrong Operator

Collection: inventory

[{item:'Apple',tags:['fruit','fresh']}]

🎯 Goal:

Find BOTH fruit AND fresh tags

❌ Broken Query:

This query has a bug!
db.inventory.find({tags:{$in:["fruit","fresh"]}})
Error: Returns wrong items
πŸ’‘ Hint:

$in vs $all

βœ“ Correct Query:

Fixed Version
db.inventory.find({tags:{$all:["fruit","fresh"]}})
πŸ“– What Was Wrong:

$in=ANY(OR), $all=ALL(AND)

Bug #22 Medium Wrong Operator

Collection: products

[{name:'Widget',discount:null},{name:'Gizmo'}]

🎯 Goal:

Find missing discount field

❌ Broken Query:

This query has a bug!
db.products.find({discount:null})
Error: Matches null too
πŸ’‘ Hint:

null vs missing

βœ“ Correct Query:

Fixed Version
db.products.find({discount:{$exists:false}})
πŸ“– What Was Wrong:

Use $exists for missing fields

Bug #23 Easy Wrong Operator

Collection: users

[{name:'Alice',age:25},{name:'Bob',age:30}]

🎯 Goal:

Find age 25,30, or 35

❌ Broken Query:

This query has a bug!
db.users.find({age:{$all:[25,30,35]}})
Error: Returns nothing
πŸ’‘ Hint:

$all is for arrays

βœ“ Correct Query:

Fixed Version
db.users.find({age:{$in:[25,30,35]}})
πŸ“– What Was Wrong:

Use $in for value matching

Bug #24 Medium Wrong Operator

Collection: posts

[{title:'Hello',content:'World'}]

🎯 Goal:

Find title contains "ello"

❌ Broken Query:

This query has a bug!
db.posts.find({title:{$like:"%ello%"}})
Error: Unknown operator
πŸ’‘ Hint:

MongoDB pattern matching

βœ“ Correct Query:

Fixed Version
db.posts.find({title:{$regex:/ello/}})
πŸ“– What Was Wrong:

Use $regex, not $like

Bug #25 Hard Wrong Operator

Collection: sales

[{items:[{name:'x'}]}]

🎯 Goal:

Find items array size=1

❌ Broken Query:

This query has a bug!
db.sales.find({items:{$size:{$eq:1}}}})
Error: $size no operators
πŸ’‘ Hint:

$size takes number

βœ“ Correct Query:

Fixed Version
db.sales.find({items:{$size:1}})
πŸ“– What Was Wrong:

$size:number, not object

Bug #26 Medium Wrong Operator

Collection: books

[{title:'Book A',author:'Smith'}]

🎯 Goal:

Find author NOT Smith

❌ Broken Query:

This query has a bug!
db.books.find({author:{$not:"Smith"}})
Error: $not needs operator
πŸ’‘ Hint:

Use $ne

βœ“ Correct Query:

Fixed Version
db.books.find({author:{$ne:"Smith"}})
πŸ“– What Was Wrong:

$ne for not equal

Bug #27 Easy Wrong Operator

Collection: items

[{name:'A',tags:['red','blue']}]

🎯 Goal:

Find EXACTLY tags [red,blue]

❌ Broken Query:

This query has a bug!
db.items.find({tags:{$all:["red","blue"]}})
Error: Matches subsets
πŸ’‘ Hint:

$all vs equality

βœ“ Correct Query:

Fixed Version
db.items.find({tags:["red","blue"]})
πŸ“– What Was Wrong:

$all checks contains, use equality for exact

Bug #28 Hard Wrong Operator

Collection: products

[{specs:{weight:5,color:'red'}}]

🎯 Goal:

Find specs.weight>3

❌ Broken Query:

This query has a bug!
db.products.find({specs:{weight:{$gt:3}}}})
Error: Returns nothing
πŸ’‘ Hint:

Use dot notation

βœ“ Correct Query:

Fixed Version
db.products.find({"specs.weight":{$gt:3}})
πŸ“– What Was Wrong:

Dot notation for nested fields

Bug #29 Medium Wrong Operator

Collection: records

[{value:'abc'},{value:'ABC'}]

🎯 Goal:

Find "abc" case-insensitive

❌ Broken Query:

This query has a bug!
db.records.find({value:"abc"})
Error: Case-sensitive
πŸ’‘ Hint:

Use regex with i flag

βœ“ Correct Query:

Fixed Version
db.records.find({value:{$regex:/^abc$/i}})
πŸ“– What Was Wrong:

Use /pattern/i for case-insensitive

Bug #30 Medium Wrong Operator

Collection: users

[{friends:['Bob','Charlie']}]

🎯 Goal:

Find users with Bob as friend

❌ Broken Query:

This query has a bug!
db.users.find({friends:{$contains:"Bob"}})
Error: Unknown $contains
πŸ’‘ Hint:

No $contains in MongoDB

βœ“ Correct Query:

Fixed Version
db.users.find({friends:"Bob"})
πŸ“– What Was Wrong:

Arrays match automatically

πŸ“Š Aggregation Pipeline Bugs (31-40)

Debug complex aggregation pipeline errors.

Bug #31 Hard Pipeline Order

Collection: sales

[{product:'A',amount:100,status:'completed'}]

🎯 Goal:

Sum by product for completed only

❌ Broken Query:

This query has a bug!
db.sales.aggregate([{$group:{_id:"$product",total:{$sum:"$amount"}}},{$match:{status:"completed"}}])
Error: status lost after $group
πŸ’‘ Hint:

Filter before grouping

βœ“ Correct Query:

Fixed Version
db.sales.aggregate([{$match:{status:"completed"}},{$group:{_id:"$product",total:{$sum:"$amount"}}}])
πŸ“– What Was Wrong:

$match BEFORE $group to filter early and use indexes

Bug #32 Medium Aggregation Error

Collection: orders

[{customer:'Alice',items:3,total:150}]

🎯 Goal:

Add 10% tax

❌ Broken Query:

This query has a bug!
db.orders.aggregate([{$project:{totalWithTax:{$multiply:["$total",1.1]}}}])
Error: Loses customer
πŸ’‘ Hint:

Include needed fields

βœ“ Correct Query:

Fixed Version
db.orders.aggregate([{$project:{customer:1,total:1,totalWithTax:{$multiply:["$total",1.1]}}}])
πŸ“– What Was Wrong:

$project excludes fields unless specified

Bug #33 Hard Aggregation Error

Collection: sales

[{date:'2024-01-15',amount:100}]

🎯 Goal:

Group by month

❌ Broken Query:

This query has a bug!
db.sales.aggregate([{$group:{_id:{$month:"date"},total:{$sum:"$amount"}}}])
Error: Expects Date
πŸ’‘ Hint:

Convert to Date

βœ“ Correct Query:

Fixed Version
db.sales.aggregate([{$group:{_id:{$month:{$toDate:"$date"}},total:{$sum:"$amount"}}}])
πŸ“– What Was Wrong:

Use $toDate for string dates

Bug #34 Medium Aggregation Error

Collection: products

[{name:'A',price:100,qty:5}]

🎯 Goal:

Calculate value (price*qty)

❌ Broken Query:

This query has a bug!
db.products.aggregate([{$project:{value:{$multiply:["price","qty"]}}}])
Error: Returns null
πŸ’‘ Hint:

Need $ for fields

βœ“ Correct Query:

Fixed Version
db.products.aggregate([{$project:{value:{$multiply:["$price","$qty"]}}}])
πŸ“– What Was Wrong:

In aggregation use $fieldName

Bug #35 Hard Aggregation Error

Collection: orders

[{items:[{name:'A',qty:2},{name:'B',qty:3}]}]

🎯 Goal:

Sum all item quantities

❌ Broken Query:

This query has a bug!
db.orders.aggregate([{$project:{total:{$sum:"$items.qty"}}}])
Error: Returns array
πŸ’‘ Hint:

$unwind first

βœ“ Correct Query:

Fixed Version
db.orders.aggregate([{$unwind:"$items"},{$group:{_id:"$_id",total:{$sum:"$items.qty"}}}])
πŸ“– What Was Wrong:

$unwind array before summing

Bug #36 Medium Aggregation Error

Collection: users

[{firstName:'John',lastName:'Doe'}]

🎯 Goal:

Create fullName

❌ Broken Query:

This query has a bug!
db.users.aggregate([{$project:{fullName:"$firstName"+" "+"$lastName"}}])
Error: Wrong concat
πŸ’‘ Hint:

Use $concat

βœ“ Correct Query:

Fixed Version
db.users.aggregate([{$project:{fullName:{$concat:["$firstName"," ","$lastName"]}}}])
πŸ“– What Was Wrong:

Use $concat for strings

Bug #37 Easy Aggregation Error

Collection: posts

[{title:'A',views:100},{title:'B',views:200}]

🎯 Goal:

Top 3 by views

❌ Broken Query:

This query has a bug!
db.posts.aggregate([{$limit:3},{$sort:{views:-1}}])
Error: Random 3
πŸ’‘ Hint:

Sort before limit

βœ“ Correct Query:

Fixed Version
db.posts.aggregate([{$sort:{views:-1}},{$limit:3}])
πŸ“– What Was Wrong:

Always sort then limit

Bug #38 Hard Aggregation Error

Collection: inventory

[{item:'A',qty:[5,10,15]}]

🎯 Goal:

Average of qty array

❌ Broken Query:

This query has a bug!
db.inventory.aggregate([{$project:{avg:{$avg:"$qty"}}}])
Error: Should work in 5.0+
πŸ’‘ Hint:

Works in modern MongoDB

βœ“ Correct Query:

Fixed Version
db.inventory.aggregate([{$project:{avg:{$avg:"$qty"}}}])
πŸ“– What Was Wrong:

Modern MongoDB supports $avg on arrays

Bug #39 Medium Aggregation Error

Collection: sales

[{product:'A',sales:[{month:1,amt:100}]}]

🎯 Goal:

Count sales entries

❌ Broken Query:

This query has a bug!
db.sales.aggregate([{$group:{_id:"$product",count:{$count:"$sales"}}}])
Error: $count no args
πŸ’‘ Hint:

Use $sum or $size

βœ“ Correct Query:

Fixed Version
db.sales.aggregate([{$project:{product:1,count:{$size:"$sales"}}}])
πŸ“– What Was Wrong:

Use $size in $project

Bug #40 Hard Aggregation Error

Collection: orders

[{customer:'Alice',total:100}]

🎯 Goal:

Filter total > average

❌ Broken Query:

This query has a bug!
db.orders.aggregate([{$match:{total:{$gt:{$avg:"$total"}}}}])
Error: Cannot use $avg in $match
πŸ’‘ Hint:

Calculate first

βœ“ Correct Query:

Fixed Version
db.orders.aggregate([{$group:{_id:null,avg:{$avg:"$total"},docs:{$push:"$$ROOT"}}},{$unwind:"$docs"},{$match:{$expr:{$gt:["$docs.total","$avg"]}}}])
πŸ“– What Was Wrong:

Calculate value first, then $match with $expr

✏️ Update Operation Errors (41-50)

Fix broken update queries.

Bug #41 Medium Update Error

Collection: counters

[{_id:1,views:100,likes:50}]

🎯 Goal:

Increment views+1, likes+2

❌ Broken Query:

This query has a bug!
db.counters.updateOne({_id:1},{$inc:{views:1},$inc:{likes:2}})
Error: Duplicate $inc
πŸ’‘ Hint:

One operator object

βœ“ Correct Query:

Fixed Version
db.counters.updateOne({_id:1},{$inc:{views:1,likes:2}})
πŸ“– What Was Wrong:

Put fields in one $inc

Bug #42 Easy Update Error

Collection: users

[{_id:1,name:'Alice',age:25}]

🎯 Goal:

Update age to 26

❌ Broken Query:

This query has a bug!
db.users.updateOne({_id:1},{age:26})
Error: Replaces doc
πŸ’‘ Hint:

Use $set

βœ“ Correct Query:

Fixed Version
db.users.updateOne({_id:1},{$set:{age:26}})
πŸ“– What Was Wrong:

Without operators, replaces doc

Bug #43 Medium Update Error

Collection: posts

[{_id:1,tags:['a','b']}]

🎯 Goal:

Add tag c to array

❌ Broken Query:

This query has a bug!
db.posts.updateOne({_id:1},{$set:{tags:"c"}})
Error: Replaces array
πŸ’‘ Hint:

Use $push

βœ“ Correct Query:

Fixed Version
db.posts.updateOne({_id:1},{$push:{tags:"c"}})
πŸ“– What Was Wrong:

Use $push to append

Bug #44 Hard Update Error

Collection: products

[{_id:1,price:100,qty:10}]

🎯 Goal:

Multiply price*1.1, decrement qty

❌ Broken Query:

This query has a bug!
db.products.updateOne({_id:1},{$mul:{price:1.1},$dec:{qty:1}})
Error: No $dec
πŸ’‘ Hint:

Use $inc with negative

βœ“ Correct Query:

Fixed Version
db.products.updateOne({_id:1},{$mul:{price:1.1},$inc:{qty:-1}})
πŸ“– What Was Wrong:

No $dec, use $inc:-1

Bug #45 Medium Update Error

Collection: items

[{_id:1,tags:['a','b','c']}]

🎯 Goal:

Remove tag b

❌ Broken Query:

This query has a bug!
db.items.updateOne({_id:1},{$pop:{tags:"b"}})
Error: $pop removes first/last
πŸ’‘ Hint:

Use $pull

βœ“ Correct Query:

Fixed Version
db.items.updateOne({_id:1},{$pull:{tags:"b"}})
πŸ“– What Was Wrong:

$pull removes by value

Bug #46 Easy Update Error

Collection: users

[{_id:1,name:'Alice'}]

🎯 Goal:

Set age only if not exists

❌ Broken Query:

This query has a bug!
db.users.updateOne({_id:1},{$set:{age:25}})
Error: Overwrites
πŸ’‘ Hint:

Check first or upsert

βœ“ Correct Query:

Fixed Version
db.users.updateOne({_id:1,age:{$exists:false}},{$set:{age:25}})
πŸ“– What Was Wrong:

Query for !exists first

Bug #47 Hard Update Error

Collection: posts

[{_id:1,tags:['a','b']}]

🎯 Goal:

Add c only if not present

❌ Broken Query:

This query has a bug!
db.posts.updateOne({_id:1},{$push:{tags:"c"}})
Error: Creates duplicate
πŸ’‘ Hint:

Use $addToSet

βœ“ Correct Query:

Fixed Version
db.posts.updateOne({_id:1},{$addToSet:{tags:"c"}})
πŸ“– What Was Wrong:

$addToSet prevents duplicates

Bug #48 Medium Update Error

Collection: records

[{_id:1,data:{a:1,b:2}}]

🎯 Goal:

Update data.a to 10

❌ Broken Query:

This query has a bug!
db.records.updateOne({_id:1},{$set:{data:{a:10}}})
Error: Replaces data
πŸ’‘ Hint:

Use dot notation

βœ“ Correct Query:

Fixed Version
db.records.updateOne({_id:1},{$set:{"data.a":10}})
πŸ“– What Was Wrong:

Use "data.a" for nested

Bug #49 Hard Update Error

Collection: users

[{_id:1,scores:[10,20,30]}]

🎯 Goal:

Increment scores[1] by 5

❌ Broken Query:

This query has a bug!
db.users.updateOne({_id:1},{$inc:{scores[1]:5}})
Error: Syntax error
πŸ’‘ Hint:

Dot notation

βœ“ Correct Query:

Fixed Version
db.users.updateOne({_id:1},{$inc:{"scores.1":5}})
πŸ“– What Was Wrong:

Use "array.index"

Bug #50 Hard Update Error

Collection: products

[{items:[{name:'A',qty:5},{name:'B',qty:10}]}]

🎯 Goal:

Increment qty for name=B

❌ Broken Query:

This query has a bug!
db.products.updateOne({_id:1,"items.name":"B"},{$inc:{"items.qty":2}})
Error: Updates all
πŸ’‘ Hint:

Use $ positional

βœ“ Correct Query:

Fixed Version
db.products.updateOne({_id:1,"items.name":"B"},{$inc:{"items.$.qty":2}})
πŸ“– What Was Wrong:

Use $ for matched element

πŸŽ‰ Debugging Mastery!

The ability to quickly spot and fix bugs is what separates junior developers from seniors. Keep practicing these patterns and you'll become a MongoDB debugging expert!

Pro Tips:

  • Always check bracket/parenthesis matching first
  • Read error messages carefully - they often tell you exactly what's wrong
  • Test complex queries in stages - build up from simple to complex
  • Use explain() to understand why a query isn't returning expected results
  • Practice debugging daily - it's the fastest way to master MongoDB