Finding Documents with Queries: Filters & Projections
A Magical Treasure Hunt in MongoDB : For beginners to Expert Level
Quick Overview: This MongoDB tutorial explains how to find documents using filters and projections. Whether you’re a beginner or an expert, you’ll learn step-by-step query examples using mongosh and MongoDB Compass to search, filter, and display data efficiently.
📘 Table of Contents
- Part 1: What Are Filters & Projections?
- Part 2: Sample Data (Let’s Load Our Heroes!)
- Part 3: Basic Filters : “Find Who?”
- Part 4: Projections : “Show Only What I Want”
- Part 5: Combine Filter + Projection
- Part 6: Using Compass : Click to Query
- Part 7: Advanced Filters (Pro Level)
- Part 8: Mini Project : Hero Search Engine!
- Part 9: Pro Tips for All Levels
- Part 10: Cheat Sheet (Print & Stick)
- Part 11: Common Mistakes & Fixes
- Final Words & Resources
- Bonus Tip for Experts 🧠
Imagine you’re in the Hero Academy Library, and you need to find one special book from thousands. You can ask:
- “Show me all fire heroes.”
- “Give me only their names and powers.”
In MongoDB, this is called querying! You use filters (what to find) and projections (what to show). This tutorial is a fun treasure hunt, super easy for a student, but packed with pro-level secrets for experts.
We’ll use:
- Our Hero Academy from before
mongosh(command line)- MongoDB Compass (click & search)
- Real images
Part 1: What Are Filters & Projections?
| Term | Real-Life Example | MongoDB Meaning |
|---|---|---|
| Filter | “Find all red toys” | Conditions to select documents |
| Projection | “Show only toy name and color” | Fields to show or hide |
Fun Fact: Filter = “Who to invite?”
Projection = “What info to print on the card?”
Part 2: Sample Data (Let’s Load Our Heroes!)
use heroAcademy
db.heroes.insertMany([
{ name: "Aarav", power: "Super Speed", level: 5, isActive: true, team: "Alpha", skills: ["run", "jump"] },
{ name: "Priya", power: "Invisibility", level: 7, isActive: true, team: "Alpha", skills: ["hide", "sneak"] },
{ name: "Rohan", power: "Fire Control", level: 4, isActive: false, team: "Beta", skills: ["flame", "shield"] },
{ name: "Sanya", power: "Telekinesis", level: 6, isActive: true, team: "Beta", skills: ["lift", "fly"] },
{ name: "Karan", power: "Ice Blast", level: 3, isActive: true, team: "Alpha", skills: ["freeze", "snow"] }
])
Part 3: Basic Filters – “Find Who?”
1. Find All Heroes
db.heroes.find()
→ Shows everything
2. Find Active Heroes
db.heroes.find({ isActive: true })
→ Only heroes with isActive: true
Like: “Show me only students who came to school today.”
3. Find by Exact Match
db.heroes.find({ power: "Fire Control" })
→ Only Rohan
4. Find by Number
db.heroes.find({ level: { $gt: 5 } })
→ Priya (7) and Sanya (6)
Operators You’ll Love:
| Operator | Meaning | Example |
|---|---|---|
| $gt | Greater than | level: { $gt: 5 } |
| $lt | Less than | level: { $lt: 4 } |
| $gte | Greater or equal | level: { $gte: 6 } |
| $lte | Less or equal | level: { $lte: 5 } |
| $ne | Not equal | team: { $ne: "Alpha" } |
| $in | In a list | name: { $in: ["Aarav", "Priya"] } |
5. Find in Arrays
db.heroes.find({ skills: "fly" })
→ Sanya (has “fly” in skills)
db.heroes.find({ skills: { $all: ["run", "jump"] } })
→ Only Aarav
6. Find in Nested Fields
db.heroes.find({ "team": "Alpha" })
Part 4: Projections: “Show Only What I Want”
By default, .find() shows all fields. Use projection to pick!
Syntax:
db.collection.find(filter, projection)
1. Show Only Name and Power
db.heroes.find(
{ isActive: true },
{ name: 1, power: 1, _id: 0 }
)
{ "name": "Aarav", "power": "Super Speed" }
{ "name": "Priya", "power": "Invisibility" }
Rules:
1 = Include this field
0 = Hide this field
Never mix 1 and 0 (except for _id)
Always hide _id with _id: 0 if not needed
2. Hide Skills
db.heroes.find(
{ team: "Alpha" },
{ skills: 0 }
)
→ Shows all except skills
Part 5: Combine Filter + Projection
db.heroes.find(
{ isActive: true, team: "Alpha" },
{ name: 1, level: 1, _id: 0 }
)
{ "name": "Aarav", "level": 5 }
{ "name": "Priya", "level": 7 }
{ "name": "Karan", "level": 3 }
Beginner Win: Like making a custom report card!
Part 6: Using Compass : Click to Query!
- Open Compass → heroAcademy → heroes
- Use Filter Bar
{ "isActive": true, "team": "Alpha" }
Compass Filter
- Use Projection
{ "name": 1, "level": 1, "_id": 0 }
Click & See! No typing needed.
Part 7: Advanced Filters (Pro Level)
1. Text Search (Need index!)
db.heroes.createIndex({ name: "text" })
db.heroes.find({ $text: { $search: "Priya" } })
Important: $text queries only work on fields that have a
text index. Each collection can have just one text index,
so make sure no other text index exists before creating a new one.
You can check existing indexes with db.heroes.getIndexes().
2. Regex (Pattern Match)
db.heroes.find({ name: /^A/ }) // Starts with A
db.heroes.find({ name: /an$/i }) // Ends with "an", case-insensitive
Note: The patterns /^A/ and /an$/i are
JavaScript regular expressions (regex).
MongoDB supports the same regex syntax used in JavaScript,
so you can easily search by text patterns like “starts with”, “ends with”, or “contains”.
3. Logical Operators
// AND (default)
db.heroes.find({ level: { $gt: 5 }, isActive: true })
// OR
db.heroes.find({
$or: [
{ power: "Fire Control" },
{ power: "Ice Blast" }
]
})
// NOT
db.heroes.find({ team: { $ne: "Alpha" } })
4. Array Queries
// Has exactly 2 skills
db.heroes.find({ skills: { $size: 2 } })
// Has skill AND level > 5
db.heroes.find({
skills: "fly",
level: { $gt: 5 }
})
5. Dot Notation (Nested)
// If hero had address:
db.heroes.find({ "address.city": "Delhi" })
Part 8: Mini Project - Hero Search Engine!
1. Find Top Heroes (level ≥ 7)
db.heroes.find(
{ level: { $gte: 7 } },
{ name: 1, power: 1, level: 1, _id: 0 }
).pretty()
2. Find Inactive Heroes
db.heroes.find(
{ isActive: false },
{ name: 1, team: 1, _id: 0 }
)
3. Find Alpha Team Flyers
db.heroes.find(
{ team: "Alpha", skills: "fly" },
{ name: 1, _id: 0 }
)
Real-World Connection:
The same query patterns you used for your Hero Academy can power real-world applications too.
For example, in an e-commerce site, you might filter products by category and price,
or in a school app, find students by grade and attendance.
MongoDB queries make these kinds of searches fast and flexible!
Part 9: Pro Tips for All Levels
For Students & Beginners
- Use Compass filter bar – just type!
- Start with { field: value }
- Always use .pretty() in mongosh
For Medium Learners
db.heroes.find()
.sort({ level: -1 }) // High to low
.limit(3) // Top 3
Count matches:
db.heroes.countDocuments({ team: "Alpha" })
For Experts
db.heroes.aggregate([
{ $match: { isActive: true } },
{ $group: { _id: "$team", count: { $sum: 1 } } }
])
Index for speed:
db.heroes.createIndex({ level: 1, team: 1 })
Use explain() to debug:
db.heroes.find({ level: 5 }).explain("executionStats")
Part 10: Cheat Sheet (Print & Stick!)
| Query Type | Example Code |
|---|---|
| Find all | db.heroes.find() |
| Filter | db.heroes.find({ level: 5 }) |
| With operator | db.heroes.find({ level: { $gt: 5 } }) |
| Projection | db.heroes.find({}, { name: 1, _id: 0 }) |
| Filter + Projection | db.heroes.find({ team: "Alpha" }, { name: 1 }) |
| Pretty print | .pretty() |
| Count | .countDocuments({}) |
Part 11: Common Mistakes & Fixes
| Mistake | Fix |
|---|---|
| Forgetting quotes | Use "power": "Fire" not power: Fire |
| Wrong field name | Check with findOne() |
| Using == instead of : | Use : in JSON: { level: 5 } |
| Forgetting _id: 0 | Add it to hide ID |
Final Words
You’re a Query Master!
You just:
Used filters to find exact heroes
Used projections to show only what you want
Hunted in shell and Compass
Learned pro tricks like $or, indexing, aggregation
Your Mission:
db.heroes.find(
{ "skills": "run" },
{ name: 1, power: 1, _id: 0 }
).pretty()
Who did you find?
You’re now a Certified MongoDB Detective!
Resources:
Bonus Tip for Experts 🧠
You can even compare values between fields within the same document
using the $expr operator, a powerful feature for complex logic.
db.heroes.find({
$expr: { $gt: ["$level", 5] }
})
This finds heroes whose level is greater than 5
without needing a fixed number in your filter!
Keep hunting treasures in your data!