Query Operators

MongoDB Query Operators

Simple exact matches are often not enough. Query Operators give your searches logic and flexibility. They allow greater-than, less-than, and array logic.

What is an Operator?

Operators always start with a dollar sign $. They are passed inside nested JSON objects. They alter how the database compares fields.

Comparison Operators

The $gt operator means "Greater Than". The $lt operator means "Less Than". Use $gte and $lte to include the equals condition.

The $in Operator

The $in operator matches any value in an array. It works like an SQL "IN" clause. It is incredibly useful for matching multiple IDs.

Logical Operators

You can combine filters using logical operators. $or finds documents matching at least one condition. $and forces multiple conditions to be strictly true.

Operator Examples:

// 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 } ] });

Element Operators

Sometimes documents lack certain fields entirely. The $exists operator checks if a field is present. The $type operator checks the field's data type.

Evaluation Operators

You can use regular expressions for text search. The $regex operator provides pattern matching. It handles partial strings and case-insensitivity.

Array Operators

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.

Summary

Query operators unlock MongoDB's true querying power. Always remember the $ prefix syntax. Combine comparison and logical operators for complex filters.

Exercise

Which operator is used to find documents where a field is "greater than" a value?