Advanced Operators & Arrays
Advanced Operators & Arrays
MongoDBโs query language goes far beyond simple equality checks. It provides a rich set of operators for comparison, logic, and deep inspection of arrays and nested objects.
๐๏ธ 1. Comparison Operators
Comparison operators allow you to filter documents based on value ranges.
Mongo Shell
// $gt (Greater Than) and $lt (Less Than)
db.products.find({
price: { $gt: 10, $lt: 50 }
});
// $in (In Array) and $nin (Not In Array)
db.users.find({
country: { $in: ["USA", "UK", "Canada"] }
});PyMongo
# $gte (Greater Than or Equal)
results = db.products.find({
"price": {"$gte": 100}
})
# $ne (Not Equal)
results = db.users.find({
"status": {"$ne": "deleted"}
})๐ 2. Logical Operators
Logical operators combine multiple query conditions.
Mongo Shell
// $or: Matches if ANY condition is true
db.users.find({
$or: [
{ role: "admin" },
{ age: { $gt: 50 } }
]
});
// $and: Explicitly require all conditions (usually implicit)
db.users.find({
$and: [
{ status: "active" },
{ email: { $exists: true } }
]
});PyMongo
# $not: Inverts the result of a sub-query
results = db.inventory.find({
"price": {"$not": {"$gt": 1.99}}
})โก 3. Array Operators
One of MongoDBโs greatest strengths is its ability to treat arrays as โfirst-class citizens.โ
in
$all: The array must contain all the specified elements.$in: The array must contain at least one of the specified elements.
$elemMatch
Selects documents if at least one element in the array matches all specified criteria. This is essential for arrays of sub-documents.
Mongo Shell
// Find posts with BOTH 'tech' and 'mongodb' tags
db.posts.find({ tags: { $all: ["tech", "mongodb"] } });
// Find users who have at least one 'admin' permission with 'write' access
db.users.find({
permissions: {
$elemMatch: { role: "admin", access: "write" }
}
});PyMongo
# $size: Find arrays of exactly 3 elements
results = db.orders.find({"items": {"$size": 3}})๐ง 4. Update Operators for Arrays
Updating data inside arrays requires specialized operators to ensure atomicity.
$push: Adds an item to an array.$addToSet: Adds an item only if it doesnโt already exist (unique).$pull: Removes all instances of a value from an array.$pop: Removes the first (-1) or last (1) element.
Mongo Shell
// Add a tag without duplicates
db.users.updateOne(
{ _id: 1 },
{ $addToSet: { tags: "knowledge-base" } }
);
// Remove specific elements
db.users.updateOne(
{ _id: 1 },
{ $pull: { tags: "obsolete" } }
);๐ก Best Practices
- Index for Equality then Range: When creating compound indexes for these queries, follow the โESRโ rule: Equality, Sort, then Range.
- Prefer or: When querying the same field for multiple values,
$inis more performant than$or. - **Use elemMatch`, a query on an array of objects might return false positives if different elements satisfy different parts of your query.