Querying
Query Cheatsheet
A quick reference for the most common MongoDB query patterns — all in one place.
Query Cheatsheet
A quick reference for every query pattern covered in this section. No long explanations — just clean, ready-to-use examples using our school system.
Basic Queries
// Find all documents
db.students.find()
// Find one document
db.students.findOne({ name: "Ali Hassan" })
// Find by _id
db.students.findOne({ _id: new ObjectId("64a1f2c3e4b0a1b2c3d4e5f6") })
// Find with exact match
db.students.find({ grade: "10th" })
// Find with multiple exact matches — implicit $and
db.students.find({ grade: "10th", enrolled: true })
// Count matching documents
db.students.countDocuments({ grade: "10th" })Projection
// Include specific fields only
db.students.find({ grade: "10th" }, { name: 1, grade: 1 })
// Exclude specific fields
db.students.find({ grade: "10th" }, { address: 0, enrollmentDate: 0 })
// Exclude _id
db.students.find({ grade: "10th" }, { name: 1, grade: 1, _id: 0 })Sorting, Limiting, Skipping
// Sort ascending
db.students.find().sort({ age: 1 })
// Sort descending
db.students.find().sort({ age: -1 })
// Sort by multiple fields
db.students.find().sort({ grade: 1, name: 1 })
// Limit results
db.students.find().limit(5)
// Skip results
db.students.find().skip(10).limit(5)
// Sort + limit + skip together
db.students.find({ enrolled: true }).sort({ name: 1 }).skip(5).limit(5)Comparison Operators
// Equal
db.students.find({ age: { $eq: 16 } })
// Not equal
db.students.find({ age: { $ne: 16 } })
// Greater than
db.students.find({ age: { $gt: 15 } })
// Greater than or equal
db.students.find({ age: { $gte: 15 } })
// Less than
db.students.find({ age: { $lt: 18 } })
// Less than or equal
db.students.find({ age: { $lte: 18 } })
// Range — between 15 and 17 inclusive
db.students.find({ age: { $gte: 15, $lte: 17 } })
// In a list of values
db.students.find({ grade: { $in: ["9th", "10th", "11th"] } })
// Not in a list of values
db.students.find({ grade: { $nin: ["9th", "12th"] } })
// Date range
db.students.find({
enrollmentDate: {
$gte: new Date("2024-01-01"),
$lte: new Date("2024-12-31")
}
})Logical Operators
// AND — explicit
db.students.find({
$and: [{ grade: "10th" }, { enrolled: true }]
})
// AND — implicit shorthand
db.students.find({ grade: "10th", enrolled: true })
// OR
db.students.find({
$or: [{ grade: "9th" }, { grade: "11th" }]
})
// NOT
db.students.find({ age: { $not: { $gt: 16 } } })
// NOR
db.students.find({
$nor: [{ grade: "9th" }, { enrolled: false }]
})
// AND combined with OR
db.students.find({
enrolled: true,
$or: [{ grade: "10th" }, { age: { $gt: 16 } }]
})Nested Fields
// Query nested field with dot notation
db.students.find({ "address.city": "Lahore" })
// Query deeply nested field
db.students.find({ "address.country": "Pakistan" })Array Queries
// Array contains a value
db.students.find({ subjects: "Math" })
// Array contains all specified values
db.students.find({ subjects: { $all: ["Math", "Physics"] } })
// Array has exact size
db.students.find({ subjects: { $size: 3 } })
// Array has at least N elements — index trick
db.students.find({ "subjects.2": { $exists: true } })
// Array of objects — elemMatch
db.students.find({
grades: {
$elemMatch: {
subject: "Math",
score: { $gt: 90 }
}
}
})
// Array of objects — failed any subject
db.students.find({
grades: {
$elemMatch: { score: { $lt: 50 } }
}
})Element Operators
// Field exists
db.students.find({ phone: { $exists: true } })
// Field does not exist
db.students.find({ phone: { $exists: false } })
// Field is a specific type
db.students.find({ age: { $type: "double" } })
db.students.find({ enrollmentDate: { $type: "date" } })
db.students.find({ subjects: { $type: "array" } })
// Field exists AND is correct type
db.students.find({
graduationDate: { $exists: true, $type: "date" }
})Evaluation Operators
// Regex — starts with
db.students.find({ name: { $regex: /^Ali/i } })
// Regex — contains
db.students.find({ name: { $regex: /ahmed/i } })
// Regex — ends with
db.teachers.find({ email: { $regex: /@school\.com$/i } })
// Compare two fields in same document
db.courses.find({
$expr: { $gt: ["$totalStudents", "$capacity"] }
})
// Text search — requires text index
db.courses.createIndex({ title: "text" })
db.courses.find({ $text: { $search: "science" } })
// Text search — exact phrase
db.courses.find({ $text: { $search: "\"computer science\"" } })
// Text search — exclude word
db.courses.find({ $text: { $search: "science -computer" } })
// Text search — sort by relevance
db.courses.find(
{ $text: { $search: "math" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })School System — Real Query Patterns
// All enrolled students sorted by name
db.students.find({ enrolled: true }).sort({ name: 1 })
// Students in 10th grade, showing name and grade only
db.students.find(
{ grade: "10th" },
{ name: 1, grade: 1, _id: 0 }
)
// Students from Lahore who are enrolled
db.students.find({ "address.city": "Lahore", enrolled: true })
// Students aged between 15 and 17 in 10th or 11th grade
db.students.find({
age: { $gte: 15, $lte: 17 },
grade: { $in: ["10th", "11th"] }
})
// Students taking both Math and Physics
db.students.find({ subjects: { $all: ["Math", "Physics"] } })
// Students who scored above 90 in any subject
db.students.find({
grades: { $elemMatch: { score: { $gt: 90 } } }
})
// Students who scored above 90 specifically in Math
db.students.find({
grades: {
$elemMatch: { subject: "Math", score: { $gt: 90 } }
}
})
// Active teachers who joined before 2018
db.teachers.find({
active: true,
joinedDate: { $lt: new Date("2018-01-01") }
})
// Courses with between 20 and 30 students
db.courses.find({ totalStudents: { $gte: 20, $lte: 30 } })
// Courses where enrollment exceeds capacity
db.courses.find({
$expr: { $gt: ["$totalStudents", "$capacity"] }
})
// Page 2 of enrolled students — 10 per page
db.students
.find({ enrolled: true })
.sort({ name: 1 })
.skip(10)
.limit(10)Operator Quick Reference
| Category | Operator | Meaning |
|---|---|---|
| Comparison | $eq | Equal |
| Comparison | $ne | Not equal |
| Comparison | $gt | Greater than |
| Comparison | $gte | Greater than or equal |
| Comparison | $lt | Less than |
| Comparison | $lte | Less than or equal |
| Comparison | $in | In a list |
| Comparison | $nin | Not in a list |
| Logical | $and | All conditions true |
| Logical | $or | Any condition true |
| Logical | $not | Condition is false |
| Logical | $nor | All conditions false |
| Element | $exists | Field exists or not |
| Element | $type | Field is a specific type |
| Array | $all | Array contains all values |
| Array | $elemMatch | One element matches all conditions |
| Array | $size | Array has exact length |
| Evaluation | $regex | Match a pattern |
| Evaluation | $expr | Compare two fields |
| Evaluation | $text | Full-text search |