MongoDB Query Operators
Introduction
Query operators in MongoDB are special elements that you can use to specify complex search conditions. They allow you to filter documents in a collection based on specific criteria such as equality, ranges, arrays, and more. Whether you need to find documents with specific values, within certain ranges, or with particular elements in an array, MongoDB's query operators provide the tools you need.
In this tutorial, we'll explore the most important MongoDB query operators, how they work, and how to use them effectively in your applications.
Understanding Query Operators
MongoDB query operators are special keys in query documents that start with a dollar sign ($
). These operators provide ways to locate data within the database beyond simple equality matches.
Query operators are divided into several categories:
- Comparison Operators: Compare values (
$eq
,$gt
,$lt
, etc.) - Logical Operators: Combine multiple queries (
$and
,$or
, etc.) - Element Operators: Check for presence or absence of fields (
$exists
,$type
) - Array Operators: Query array fields (
$in
,$all
, etc.) - Evaluation Operators: Perform specific evaluations (
$regex
,$mod
, etc.)
Let's explore each category with practical examples.
Comparison Operators
Comparison operators allow you to find documents with fields that match specific values.
Common Comparison Operators
Operator | Description |
---|---|
$eq | Matches values equal to the specified value |
$ne | Matches values not equal to the specified value |
$gt | Matches values greater than the specified value |
$gte | Matches values greater than or equal to the specified value |
$lt | Matches values less than the specified value |
$lte | Matches values less than or equal to the specified value |
$in | Matches any of the values in an array |
$nin | Matches none of the values in an array |
Examples
Let's assume we have a collection of products:
// Sample document in the products collection
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "Laptop",
price: 999.99,
category: "Electronics",
stock: 15,
ratings: [4.5, 4.8, 3.9, 5.0]
}
Find products with a price greater than $500
db.products.find({ price: { $gt: 500 } })
Output:
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"stock": 15,
"ratings": [4.5, 4.8, 3.9, 5.0]
}
Find products with low stock (less than or equal to 10)
db.products.find({ stock: { $lte: 10 } })
Find products that belong to specific categories
db.products.find({ category: { $in: ["Electronics", "Computers"] } })
Find products with a price between 1000
db.products.find({
price: {
$gte: 100,
$lte: 1000
}
})
Logical Operators
Logical operators allow you to create complex queries by combining multiple conditions.
Common Logical Operators
Operator | Description |
---|---|
$and | Joins query clauses with a logical AND |
$or | Joins query clauses with a logical OR |
$not | Inverts the effect of a query expression |
$nor | Joins query clauses with a logical NOR |
Examples
Find expensive electronics (price > $500 AND category is "Electronics")
db.products.find({
$and: [
{ price: { $gt: 500 } },
{ category: "Electronics" }
]
})
You can also write this more concisely:
db.products.find({
price: { $gt: 500 },
category: "Electronics"
})
Find products that are either electronics OR have a rating of 5.0
db.products.find({
$or: [
{ category: "Electronics" },
{ ratings: 5.0 }
]
})
Find products that aren't in the "Clothing" category
db.products.find({
category: { $not: { $eq: "Clothing" } }
})
Element Operators
Element operators help you match documents based on the presence, absence, or type of fields.
Common Element Operators
Operator | Description |
---|---|
$exists | Matches documents with or without a specific field |
$type | Matches documents where the field is of a specified BSON type |
Examples
Find products that have a "discount" field
db.products.find({ discount: { $exists: true } })
Find products where price is a decimal (double) type
db.products.find({ price: { $type: "double" } })
Array Operators
Array operators provide special capabilities for querying arrays in documents.
Common Array Operators
Operator | Description |
---|---|
$all | Matches arrays containing all the specified elements |
$elemMatch | Matches documents containing an array field with at least one element that matches all criteria |
$size | Matches arrays with the specified number of elements |
Examples
Find products that have both ratings 4.5 and 5.0
db.products.find({
ratings: { $all: [4.5, 5.0] }
})
Find products with exactly 4 ratings
db.products.find({
ratings: { $size: 4 }
})
Using $elemMatch with a more complex example
Let's assume we have a collection with documents containing review data:
// Sample document in the products collection with reviews
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "Laptop",
reviews: [
{ user: "user1", rating: 4.5, verified: true },
{ user: "user2", rating: 3.0, verified: false },
{ user: "user3", rating: 5.0, verified: true }
]
}
To find products with at least one verified review with a rating over 4:
db.products.find({
reviews: {
$elemMatch: {
rating: { $gt: 4 },
verified: true
}
}
})
Evaluation Operators
Evaluation operators perform special operations on fields to determine a match.
Common Evaluation Operators
Operator | Description |
---|---|
$regex | Matches documents where string fields match a regular expression |
$mod | Matches documents where a field value divided by a divisor has a specified remainder |
$text | Performs text search |
$where | Matches documents that satisfy a JavaScript expression |
Examples
Find products with names containing "phone" (case insensitive)
db.products.find({
name: { $regex: /phone/i }
})
Find products where stock divided by 5 has remainder 0 (i.e., stock is divisible by 5)
db.products.find({
stock: { $mod: [5, 0] }
})
Real-World Application Examples
E-commerce Product Filtering
Let's implement a realistic e-commerce product filtering system:
// Find electronics priced between $200-$600, in stock, with good ratings
db.products.find({
category: "Electronics",
price: { $gte: 200, $lte: 600 },
stock: { $gt: 0 },
"ratings.average": { $gte: 4.0 }
})
User Analytics Application
Imagine a user analytics system:
// Find active users who registered in the last 30 days and have more than 5 logins
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
db.users.find({
status: "active",
registrationDate: { $gte: thirtyDaysAgo },
loginCount: { $gt: 5 }
})
Content Management System
For a blog or content platform:
// Find published articles containing "MongoDB" in the title and at least 5 comments
db.articles.find({
status: "published",
title: { $regex: /MongoDB/i },
comments: { $size: { $gte: 5 } }
})
Combining Multiple Operators
MongoDB allows combining multiple operators for complex queries:
// Find products that are:
// - either electronics with price over $1000
// - or clothing items with a discount
db.products.find({
$or: [
{
category: "Electronics",
price: { $gt: 1000 }
},
{
category: "Clothing",
discount: { $exists: true }
}
]
})
Query Performance Considerations
When using query operators, keep these performance tips in mind:
- Create indexes for fields used frequently in queries
- Avoid using regexes without anchors (e.g.,
^
) as they cannot use indexes effectively - Limit the result set size using
.limit()
when possible - Use more specific conditions first in
$or
queries - Monitor query performance using
explain()
method
Example using explain()
:
db.products.find({ price: { $gt: 500 } }).explain("executionStats")
Summary
MongoDB query operators provide powerful tools to filter and find documents based on complex criteria. We've covered:
- Comparison operators like
$eq
,$gt
,$lt
for basic comparisons - Logical operators like
$and
,$or
for combining conditions - Element operators like
$exists
,$type
for checking field properties - Array operators like
$all
,$elemMatch
for working with arrays - Evaluation operators like
$regex
for advanced evaluations
Using these operators effectively will help you build sophisticated queries that match exactly what you need from your MongoDB collections.
Additional Resources and Exercises
Further Reading
Practice Exercises
- Create a collection called
movies
with fields for title, year, genres (array), and rating. - Write a query to find all movies from the 2000s (2000-2009) with a rating above 8.
- Find movies that are either comedies OR have "adventure" in their title.
- Find movies that have exactly 3 genres listed.
- Find movies released after 2015 that don't have the genre "Horror".
These exercises will help you practice combining various MongoDB query operators to create effective filtering queries.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)