CRUD: Read
Reading data is the most common database operation—and the one that can make or break your application’s performance. MongoDB provides a powerful query language that lets you find exactly the data you need, efficiently.
Understanding MongoDB Queries
Unlike SQL’s string-based queries, MongoDB uses JSON-like query documents. This approach is:
- Type-safe: No SQL injection vulnerabilities from string concatenation
- Composable: Build complex queries programmatically
- Intuitive: If you know JSON, you can write queries
Every query should be intentional. Poorly written queries can:
- Scan millions of documents instead of using indexes
- Consume excessive memory on large result sets
- Block other operations due to collection-level locks (in older versions)
Always use projection to return only the fields you need, and consider indexes for frequently queried fields. We’ll cover indexing in a later chapter.
Basic Query Methods
Read operations retrieve documents from a collection; i.e., query a collection for documents.
find() and findOne()
find(filter): Returns a cursor to the matching documents.
findOne(filter): Returns the first matching document.
// Find all documents
db.users.find({})
// Find users with name "Alice"
db.users.find({ name: "Alice" })
Comparison Operators
$eq: Equal to
$ne: Not equal to
$gt: Greater than
$gte: Greater than or equal to
$lt: Less than
$lte: Less than or equal to
$in: In an array
$nin: Not in an array
Examples:
// Age > 25
db.users.find({ age: { $gt: 25 } })
// Status is "active" OR "pending"
db.users.find({ status: { $in: ["active", "pending"] } })
Logical Operators
$or: Joins query clauses with a logical OR
$and: Joins query clauses with a logical AND
$not: Inverts the effect of a query expression
$nor: Joins query clauses with a logical NOR
Example:
// Age < 30 AND status = "active"
db.users.find({
$and: [
{ age: { $lt: 30 } },
{ status: "active" }
]
})
// Implicit AND (shorter syntax)
db.users.find({ age: { $lt: 30 }, status: "active" })
Element Operators
$exists: Matches documents that have the specified field.
$type: Selects documents if a field is of the specified type.
// Find users who have a "phone" field
db.users.find({ phone: { $exists: true } })
Projection
Projection determines which fields are returned in the matching documents.
// Return only name and age (exclude _id)
db.users.find({}, { name: 1, age: 1, _id: 0 })
Summary
- Use
find() to query data.
- Use comparison operators like
$gt, $lt, $in for filtering.
- Use logical operators like
$or, $and for complex logic.
- Use Projection to limit the fields returned.