iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Query Operators

Mongo query operators start with $. They live inside the filter document — comparison, logical, element, array, evaluation. Composing them is how Mongo expresses everything a SQL WHERE would.

The operators you reach for daily

EXAMPLE
// Comparison
db.users.find({ age: { $gt: 18 } });            // greater than
db.users.find({ age: { $gte: 18, $lte: 65 } }); // range
db.users.find({ role: { $ne: 'banned' } });       // not equal
db.users.find({ role: { $in: ['admin', 'editor'] } });
db.users.find({ role: { $nin: ['banned', 'pending'] } });

// Logical
db.users.find({
    $and: [{ active: true }, { age: { $gte: 18 } }],
});
db.users.find({
    $or:  [{ role: 'admin' }, { score: { $gte: 1000 } }],
});
db.users.find({
    $nor: [{ banned: true }, { suspended: true }],
});

// Element
db.users.find({ email:   { $exists: true } });
db.users.find({ deleted: { $exists: false } });
db.users.find({ age:     { $type: 'int' } });

// Array
db.posts.find({ tags: 'sql' });                     // 'sql' in tags
db.posts.find({ tags: { $all: ['sql', 'fast'] } });
db.posts.find({ tags: { $size: 3 } });
db.users.find({ logins: { $elemMatch: { ip: '1.2.3.4', success: false } } });

// Evaluation
db.users.find({ email: /@example\.com$/ });        // regex
db.users.find({ $where: 'this.points > this.spent' }); // JS — slow, avoid in prod
db.users.find({
    $expr: { $gt: ['$balance', '$threshold'] }, // compare two fields
});

Why it matters

\$expr lets you compare two FIELDS in the same document — something plain operators can’t do. It’s the bridge between filters and the aggregation pipeline.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// $eq $ne $gt $gte $lt $lte $in $nin
// $and $or $not $nor
// $exists $type $regex
db.products.find({ price: { $gte: 10, $lte: 50 } });
Try it Yourself »

Discussion

Loading…