π 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.
- 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
- 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
β οΈ Syntax Errors (1-10)
These queries have syntax problems that prevent them from running.
Collection: students
[{_id:1,name:'Alice',grade:'A'},{_id:2,name:'Bob',grade:'B'}]
π― Goal:
Find students with grade A
β Broken Query:
db.students.find({grade:'A'})
π‘ Hint:
Check quote marks
β Correct Query:
db.students.find({grade:"A"})
π What Was Wrong:
Use double quotes for strings in MongoDB
Collection: products
[{_id:1,name:'Laptop',price:1200},{_id:2,name:'Mouse',price:25}]
π― Goal:
Find products price > 50
β Broken Query:
db.products.find({price:{$gt 50}})
π‘ Hint:
Check operator syntax
β Correct Query:
db.products.find({price:{$gt:50}})
π What Was Wrong:
Missing colon after $gt operator
Collection: orders
[{_id:1,customer:'Alice',total:150}]
π― Goal:
Find orders for Alice with projection
β Broken Query:
db.orders.find({customer:"Alice"},{customer:1,total:1,_id:0}
π‘ Hint:
Count parentheses
β Correct Query:
db.orders.find({customer:"Alice"},{customer:1,total:1,_id:0})
π What Was Wrong:
Missing closing parenthesis
Collection: employees
[{name:'John',dept:'IT',salary:80000}]
π― Goal:
Find IT employees, sort by salary desc
β Broken Query:
db.employees.find({dept:"IT"}).sort{salary:-1}
π‘ Hint:
Check method chaining
β Correct Query:
db.employees.find({dept:"IT"}).sort({salary:-1})
π What Was Wrong:
Missing parentheses around sort()
Collection: books
[{title:'MongoDB',pages:320},{title:'Node',pages:280}]
π― Goal:
Find books 300-400 pages
β Broken Query:
db.books.find({pages:{$gte:300,$lte 400}})
π‘ Hint:
Compare $gte vs $lte syntax
β Correct Query:
db.books.find({pages:{$gte:300,$lte:400}})
π What Was Wrong:
Missing colon after $lte
Collection: users
[{username:'alice',status:'active'}]
π― Goal:
Find active users
β Broken Query:
db.users.find({status:"active")
π‘ Hint:
Check curly braces
β Correct Query:
db.users.find({status:"active"})
π What Was Wrong:
Missing closing brace
Collection: inventory
[{item:'apple',qty:50,price:2.5}]
π― Goal:
Find qty>20 AND price<3
β Broken Query:
db.inventory.find({qty:{$gt:20}price:{$lt:3}})
π‘ Hint:
What separates conditions?
β Correct Query:
db.inventory.find({qty:{$gt:20},price:{$lt:3}})
π What Was Wrong:
Missing comma between conditions
Collection: posts
[{title:'Hello',likes:10}]
π― Goal:
Update likes to 30
β Broken Query:
db.posts.updateOne({_id:1},{set:{likes:30}})
π‘ Hint:
Check operator name
β Correct Query:
db.posts.updateOne({_id:1},{$set:{likes:30}})
π What Was Wrong:
Missing $ before set
Collection: tasks
[{name:'A',tags:['urgent','work']}]
π― Goal:
Find tasks with urgent tag
β Broken Query:
db.tasks.find({tags:"urgent")
π‘ Hint:
Match braces
β Correct Query:
db.tasks.find({tags:"urgent"})
π What Was Wrong:
Missing closing brace
Collection: sales
[{product:'A',amount:100}]
π― Goal:
Find amount 100 OR 200
β Broken Query:
db.sales.find({amount:{$or:[100,200]}})
π‘ Hint:
$or placement
β Correct Query:
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.
Collection: products
[{name:'Laptop',price:1200,inStock:true},{name:'Mouse',price:25,inStock:false}]
π― Goal:
Find inStock OR price<100
β Broken Query:
db.products.find({inStock:true,price:{$lt:100}})
π‘ Hint:
Multiple conditions use AND
β Correct Query:
db.products.find({$or:[{inStock:true},{price:{$lt:100}}]})
π What Was Wrong:
Use $or for OR logic
Collection: students
[{name:'Alice',scores:[85,90,88]}]
π― Goal:
Find students with score 90
β Broken Query:
db.students.find({scores:90})
π‘ Hint:
Be more explicit
β Correct Query:
db.students.find({scores:{$eq:90}})
π What Was Wrong:
Use $eq or $in for clarity
Collection: orders
[{customer:'Alice',total:150},{customer:'Bob',total:50},{customer:'Charlie',total:200}]
π― Goal:
Find top 2 by total
β Broken Query:
db.orders.find().limit(2).sort({total:-1})
π‘ Hint:
Sort before limit!
β Correct Query:
db.orders.find().sort({total:-1}).limit(2)
π What Was Wrong:
CRITICAL: sort() before limit()
Collection: users
[{age:25,city:'NYC'},{age:30,city:'LA'}]
π― Goal:
Find age 25 in LA
β Broken Query:
db.users.find({age:25}).find({city:"LA"})
π‘ Hint:
One find() call
β Correct Query:
db.users.find({age:25,city:"LA"})
π What Was Wrong:
Multiple conditions in one find()
Collection: items
[{qty:5,tags:['a','b']},{qty:10,tags:['b','c']}]
π― Goal:
Find qty>=5 AND tag b
β Broken Query:
db.items.find({qty:{$gte:5},tags:["b"]})
π‘ Hint:
Array equality vs contains
β Correct Query:
db.items.find({qty:{$gte:5},tags:"b"})
π What Was Wrong:
tags:["b"] checks equality, tags:"b" checks contains
Collection: employees
[{name:'John',dept:'IT'},{name:'Sarah',dept:'HR'}]
π― Goal:
Find NOT in IT
β Broken Query:
db.employees.find({dept:{$not:"IT"}})
π‘ Hint:
$not vs $ne
β Correct Query:
db.employees.find({dept:{$ne:"IT"}})
π What Was Wrong:
Use $ne for not equal
Collection: posts
[{views:100,likes:20},{views:50,likes:30}]
π― Goal:
Find views>75 OR likes>25
β Broken Query:
db.posts.find({views:{$gt:75},likes:{$gt:25}})
π‘ Hint:
AND vs OR
β Correct Query:
db.posts.find({$or:[{views:{$gt:75}},{likes:{$gt:25}}]})
π What Was Wrong:
Comma = AND, use $or
Collection: records
[{score:'95'},{score:85}]
π― Goal:
Find score>90
β Broken Query:
db.records.find({score:{$gt:90}})
π‘ Hint:
Check data types
β Correct Query:
db.records.find({score:{$gt:"90"}})
π What Was Wrong:
Match types: "95" vs 95
Collection: accounts
[{balance:100},{balance:200}]
π― Goal:
Get average balance
β Broken Query:
db.accounts.find({}).avg("balance")
π‘ Hint:
Use aggregation
β Correct Query:
db.accounts.aggregate([{$group:{_id:null,avg:{$avg:"$balance"}}}])
π What Was Wrong:
Use $avg in aggregation
Collection: inventory
[{item:'A',qty:[5,10,15]}]
π― Goal:
Find ANY qty>12
β Broken Query:
db.inventory.find({qty:{$gt:12}})
π‘ Hint:
Be explicit for arrays
β Correct Query:
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.
Collection: inventory
[{item:'Apple',tags:['fruit','fresh']}]
π― Goal:
Find BOTH fruit AND fresh tags
β Broken Query:
db.inventory.find({tags:{$in:["fruit","fresh"]}})
π‘ Hint:
$in vs $all
β Correct Query:
db.inventory.find({tags:{$all:["fruit","fresh"]}})
π What Was Wrong:
$in=ANY(OR), $all=ALL(AND)
Collection: products
[{name:'Widget',discount:null},{name:'Gizmo'}]
π― Goal:
Find missing discount field
β Broken Query:
db.products.find({discount:null})
π‘ Hint:
null vs missing
β Correct Query:
db.products.find({discount:{$exists:false}})
π What Was Wrong:
Use $exists for missing fields
Collection: users
[{name:'Alice',age:25},{name:'Bob',age:30}]
π― Goal:
Find age 25,30, or 35
β Broken Query:
db.users.find({age:{$all:[25,30,35]}})
π‘ Hint:
$all is for arrays
β Correct Query:
db.users.find({age:{$in:[25,30,35]}})
π What Was Wrong:
Use $in for value matching
Collection: posts
[{title:'Hello',content:'World'}]
π― Goal:
Find title contains "ello"
β Broken Query:
db.posts.find({title:{$like:"%ello%"}})
π‘ Hint:
MongoDB pattern matching
β Correct Query:
db.posts.find({title:{$regex:/ello/}})
π What Was Wrong:
Use $regex, not $like
Collection: sales
[{items:[{name:'x'}]}]
π― Goal:
Find items array size=1
β Broken Query:
db.sales.find({items:{$size:{$eq:1}}}})
π‘ Hint:
$size takes number
β Correct Query:
db.sales.find({items:{$size:1}})
π What Was Wrong:
$size:number, not object
Collection: books
[{title:'Book A',author:'Smith'}]
π― Goal:
Find author NOT Smith
β Broken Query:
db.books.find({author:{$not:"Smith"}})
π‘ Hint:
Use $ne
β Correct Query:
db.books.find({author:{$ne:"Smith"}})
π What Was Wrong:
$ne for not equal
Collection: items
[{name:'A',tags:['red','blue']}]
π― Goal:
Find EXACTLY tags [red,blue]
β Broken Query:
db.items.find({tags:{$all:["red","blue"]}})
π‘ Hint:
$all vs equality
β Correct Query:
db.items.find({tags:["red","blue"]})
π What Was Wrong:
$all checks contains, use equality for exact
Collection: products
[{specs:{weight:5,color:'red'}}]
π― Goal:
Find specs.weight>3
β Broken Query:
db.products.find({specs:{weight:{$gt:3}}}})
π‘ Hint:
Use dot notation
β Correct Query:
db.products.find({"specs.weight":{$gt:3}})
π What Was Wrong:
Dot notation for nested fields
Collection: records
[{value:'abc'},{value:'ABC'}]
π― Goal:
Find "abc" case-insensitive
β Broken Query:
db.records.find({value:"abc"})
π‘ Hint:
Use regex with i flag
β Correct Query:
db.records.find({value:{$regex:/^abc$/i}})
π What Was Wrong:
Use /pattern/i for case-insensitive
Collection: users
[{friends:['Bob','Charlie']}]
π― Goal:
Find users with Bob as friend
β Broken Query:
db.users.find({friends:{$contains:"Bob"}})
π‘ Hint:
No $contains in MongoDB
β Correct Query:
db.users.find({friends:"Bob"})
π What Was Wrong:
Arrays match automatically
π Aggregation Pipeline Bugs (31-40)
Debug complex aggregation pipeline errors.
Collection: sales
[{product:'A',amount:100,status:'completed'}]
π― Goal:
Sum by product for completed only
β Broken Query:
db.sales.aggregate([{$group:{_id:"$product",total:{$sum:"$amount"}}},{$match:{status:"completed"}}])
π‘ Hint:
Filter before grouping
β Correct Query:
db.sales.aggregate([{$match:{status:"completed"}},{$group:{_id:"$product",total:{$sum:"$amount"}}}])
π What Was Wrong:
$match BEFORE $group to filter early and use indexes
Collection: orders
[{customer:'Alice',items:3,total:150}]
π― Goal:
Add 10% tax
β Broken Query:
db.orders.aggregate([{$project:{totalWithTax:{$multiply:["$total",1.1]}}}])
π‘ Hint:
Include needed fields
β Correct Query:
db.orders.aggregate([{$project:{customer:1,total:1,totalWithTax:{$multiply:["$total",1.1]}}}])
π What Was Wrong:
$project excludes fields unless specified
Collection: sales
[{date:'2024-01-15',amount:100}]
π― Goal:
Group by month
β Broken Query:
db.sales.aggregate([{$group:{_id:{$month:"date"},total:{$sum:"$amount"}}}])
π‘ Hint:
Convert to Date
β Correct Query:
db.sales.aggregate([{$group:{_id:{$month:{$toDate:"$date"}},total:{$sum:"$amount"}}}])
π What Was Wrong:
Use $toDate for string dates
Collection: products
[{name:'A',price:100,qty:5}]
π― Goal:
Calculate value (price*qty)
β Broken Query:
db.products.aggregate([{$project:{value:{$multiply:["price","qty"]}}}])
π‘ Hint:
Need $ for fields
β Correct Query:
db.products.aggregate([{$project:{value:{$multiply:["$price","$qty"]}}}])
π What Was Wrong:
In aggregation use $fieldName
Collection: orders
[{items:[{name:'A',qty:2},{name:'B',qty:3}]}]
π― Goal:
Sum all item quantities
β Broken Query:
db.orders.aggregate([{$project:{total:{$sum:"$items.qty"}}}])
π‘ Hint:
$unwind first
β Correct Query:
db.orders.aggregate([{$unwind:"$items"},{$group:{_id:"$_id",total:{$sum:"$items.qty"}}}])
π What Was Wrong:
$unwind array before summing
Collection: users
[{firstName:'John',lastName:'Doe'}]
π― Goal:
Create fullName
β Broken Query:
db.users.aggregate([{$project:{fullName:"$firstName"+" "+"$lastName"}}])
π‘ Hint:
Use $concat
β Correct Query:
db.users.aggregate([{$project:{fullName:{$concat:["$firstName"," ","$lastName"]}}}])
π What Was Wrong:
Use $concat for strings
Collection: posts
[{title:'A',views:100},{title:'B',views:200}]
π― Goal:
Top 3 by views
β Broken Query:
db.posts.aggregate([{$limit:3},{$sort:{views:-1}}])
π‘ Hint:
Sort before limit
β Correct Query:
db.posts.aggregate([{$sort:{views:-1}},{$limit:3}])
π What Was Wrong:
Always sort then limit
Collection: inventory
[{item:'A',qty:[5,10,15]}]
π― Goal:
Average of qty array
β Broken Query:
db.inventory.aggregate([{$project:{avg:{$avg:"$qty"}}}])
π‘ Hint:
Works in modern MongoDB
β Correct Query:
db.inventory.aggregate([{$project:{avg:{$avg:"$qty"}}}])
π What Was Wrong:
Modern MongoDB supports $avg on arrays
Collection: sales
[{product:'A',sales:[{month:1,amt:100}]}]
π― Goal:
Count sales entries
β Broken Query:
db.sales.aggregate([{$group:{_id:"$product",count:{$count:"$sales"}}}])
π‘ Hint:
Use $sum or $size
β Correct Query:
db.sales.aggregate([{$project:{product:1,count:{$size:"$sales"}}}])
π What Was Wrong:
Use $size in $project
Collection: orders
[{customer:'Alice',total:100}]
π― Goal:
Filter total > average
β Broken Query:
db.orders.aggregate([{$match:{total:{$gt:{$avg:"$total"}}}}])
π‘ Hint:
Calculate first
β Correct Query:
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.
Collection: counters
[{_id:1,views:100,likes:50}]
π― Goal:
Increment views+1, likes+2
β Broken Query:
db.counters.updateOne({_id:1},{$inc:{views:1},$inc:{likes:2}})
π‘ Hint:
One operator object
β Correct Query:
db.counters.updateOne({_id:1},{$inc:{views:1,likes:2}})
π What Was Wrong:
Put fields in one $inc
Collection: users
[{_id:1,name:'Alice',age:25}]
π― Goal:
Update age to 26
β Broken Query:
db.users.updateOne({_id:1},{age:26})
π‘ Hint:
Use $set
β Correct Query:
db.users.updateOne({_id:1},{$set:{age:26}})
π What Was Wrong:
Without operators, replaces doc
Collection: posts
[{_id:1,tags:['a','b']}]
π― Goal:
Add tag c to array
β Broken Query:
db.posts.updateOne({_id:1},{$set:{tags:"c"}})
π‘ Hint:
Use $push
β Correct Query:
db.posts.updateOne({_id:1},{$push:{tags:"c"}})
π What Was Wrong:
Use $push to append
Collection: products
[{_id:1,price:100,qty:10}]
π― Goal:
Multiply price*1.1, decrement qty
β Broken Query:
db.products.updateOne({_id:1},{$mul:{price:1.1},$dec:{qty:1}})
π‘ Hint:
Use $inc with negative
β Correct Query:
db.products.updateOne({_id:1},{$mul:{price:1.1},$inc:{qty:-1}})
π What Was Wrong:
No $dec, use $inc:-1
Collection: items
[{_id:1,tags:['a','b','c']}]
π― Goal:
Remove tag b
β Broken Query:
db.items.updateOne({_id:1},{$pop:{tags:"b"}})
π‘ Hint:
Use $pull
β Correct Query:
db.items.updateOne({_id:1},{$pull:{tags:"b"}})
π What Was Wrong:
$pull removes by value
Collection: users
[{_id:1,name:'Alice'}]
π― Goal:
Set age only if not exists
β Broken Query:
db.users.updateOne({_id:1},{$set:{age:25}})
π‘ Hint:
Check first or upsert
β Correct Query:
db.users.updateOne({_id:1,age:{$exists:false}},{$set:{age:25}})
π What Was Wrong:
Query for !exists first
Collection: posts
[{_id:1,tags:['a','b']}]
π― Goal:
Add c only if not present
β Broken Query:
db.posts.updateOne({_id:1},{$push:{tags:"c"}})
π‘ Hint:
Use $addToSet
β Correct Query:
db.posts.updateOne({_id:1},{$addToSet:{tags:"c"}})
π What Was Wrong:
$addToSet prevents duplicates
Collection: records
[{_id:1,data:{a:1,b:2}}]
π― Goal:
Update data.a to 10
β Broken Query:
db.records.updateOne({_id:1},{$set:{data:{a:10}}})
π‘ Hint:
Use dot notation
β Correct Query:
db.records.updateOne({_id:1},{$set:{"data.a":10}})
π What Was Wrong:
Use "data.a" for nested
Collection: users
[{_id:1,scores:[10,20,30]}]
π― Goal:
Increment scores[1] by 5
β Broken Query:
db.users.updateOne({_id:1},{$inc:{scores[1]:5}})
π‘ Hint:
Dot notation
β Correct Query:
db.users.updateOne({_id:1},{$inc:{"scores.1":5}})
π What Was Wrong:
Use "array.index"
Collection: products
[{items:[{name:'A',qty:5},{name:'B',qty:10}]}]
π― Goal:
Increment qty for name=B
β Broken Query:
db.products.updateOne({_id:1,"items.name":"B"},{$inc:{"items.qty":2}})
π‘ Hint:
Use $ positional
β Correct Query:
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