Query Operators & Filtering

🍁 MongoDBLesson 5Beginner

MongoDB query operators enable complex filtering based on numeric ranges, logic conditions, array matching, and regex patterns.

1 Filtering Operators
JavaScript — Filter Operators
# Find users older than 21 ($gt = greater than)
db.users.find({ age: { $gt: 21 } });

# Find users matching specific ages ($in)
db.users.find({ age: { $in: [18, 21, 25] } });

# Logical AND query matching multiple fields ($and)
db.users.find({ 
  $and: [
    { age: { $gte: 20 } },
    { age: { $lte: 30 } }
  ]
});

# Regular expressions for string pattern search ($regex)
db.users.find({ name: { $regex: "^Bal", $options: "i" } });
2 Common Operators
OperatorMeaning
$eq / $neEquals / Not Equals
$gt / $gteGreater Than / Greater Than or Equal
$lt / $lteLess Than / Less Than or Equal
$in / $ninIn Array / Not In Array
3 Code Challenge
Challenge: Write a query finding all products priced between $100 and $500, ordered from lowest to highest price (hint: use .sort({ price: 1 })).