Simple exact matches are often not enough. Query Operators give your searches logic and flexibility. They allow greater-than, less-than, and array logic.
Operators always start with a dollar sign $. They are passed inside nested JSON objects. They alter how the database compares fields.
The $gt operator means "Greater Than". The $lt operator means "Less Than". Use $gte and $lte to include the equals condition.
The $in operator matches any value in an array. It works like an SQL "IN" clause. It is incredibly useful for matching multiple IDs.
You can combine filters using logical operators. $or finds documents matching at least one condition. $and forces multiple conditions to be strictly true.
// Find users older than 25
db.users.find({ age: { $gt: 25 } });
// Find users in specific cities
db.users.find({ city: { $in: ["London", "Paris"] } });
// Find users who are either admins or active
db.users.find({
$or: [ { role: "admin" }, { active: true } ]
});
Sometimes documents lack certain fields entirely. The $exists operator checks if a field is present. The $type operator checks the field's data type.
You can use regular expressions for text search. The $regex operator provides pattern matching. It handles partial strings and case-insensitivity.
Arrays are first-class citizens in MongoDB. The $all operator ensures an array contains specific items. The $size operator matches arrays by their exact length.
Query operators unlock MongoDB's true querying power. Always remember the $ prefix syntax. Combine comparison and logical operators for complex filters.
Which operator is used to find documents where a field is "greater than" a value?