LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1318 min read

Query Operators

Filter documents with comparison, logical, and element operators — $gt, $in, $and, $exists, and more.

Comparison Operators

Comparison operators, prefixed with $, express conditions beyond exact equality.

OperatorMeaningExample
$eqEqual to{ age: { $eq: 28 } }
$neNot equal to{ status: { $ne: "archived" } }
$gt / $gteGreater than / or equal to{ age: { $gte: 18 } }
$lt / $lteLess than / or equal to{ price: { $lt: 100 } }
$inMatches any value in a list{ status: { $in: ["active", "pending"] } }
$ninMatches none of the values in a list{ status: { $nin: ["archived", "deleted"] } }
db.products.find({ price: { $gte: 20, $lte: 100 } }); // price between 20 and 100

Logical Operators

$and, $or, and $not combine multiple conditions. Note that listing multiple fields in one query document is already an implicit $and.

// Implicit AND — both conditions must match
db.products.find({ category: "electronics", inStock: true });
// Explicit $or
db.products.find({
$or: [{ category: "electronics" }, { price: { $lt: 10 } }],
});

Element Operators

$exists and $type check for a field's presence or its BSON type, rather than its value.

db.users.find({ phoneNumber: { $exists: true } }); // has a phoneNumber field at all
db.users.find({ age: { $type: "int" } }); // age is stored as an integer

Array Operators

$all and $size query array fields specifically.

db.posts.find({ tags: { $all: ["mongodb", "database"] } }); // contains BOTH tags
db.posts.find({ tags: { $size: 3 } }); // exactly 3 tags
Querying an Array Field Without an Operator

{ tags: "mongodb" } matches any document where "mongodb" appears anywhere in the tags array — MongoDB automatically checks array membership for a plain equality match against an array field.

Common Beginner Mistakes

Forgetting operators are nested inside the field, not the top level

It's { age: { $gte: 18 } }, not { $gte: { age: 18 } } — the operator applies to a specific field's value.

Using multiple top-level $or blocks expecting them to combine as AND automatically

Multiple conditions on the same field need to be combined explicitly with $and when the implicit merge behavior isn't what you want.

FAQs

Conceptually yes — they express the same kinds of filtering conditions, just as a nested JSON-like query document instead of SQL syntax.

Yes — comparison operators typically appear nested inside logical operators like $or/$and for more complex conditions.

Summary

Comparison, logical, element, and array operators together give you precise, expressive filtering well beyond simple equality. Next, you'll learn projection, for controlling which fields a query actually returns.

Next Lesson →

Projection