Lesson 6 of 18

Query Operators

Comparison Operators

MongoDB provides operators for comparing values in queries.

Example
// $eq — equal (default)
db.products.find({ price: { $eq: 999 } })

// $ne — not equal
db.products.find({ category: { $ne: "Furniture" } })

// $gt, $gte — greater than, greater or equal
db.products.find({ price: { $gt: 100 } })
db.products.find({ price: { $gte: 100 } })

// $lt, $lte — less than, less or equal
db.products.find({ price: { $lt: 500 } })

// $in — matches any value in array
db.products.find({ category: { $in: ["Electronics", "Furniture"] } })

// $nin — not in array
db.products.find({ category: { $nin: ["Clothing"] } })

Logical Operators

Combine multiple conditions with logical operators.

Example
// $and — all conditions must match
db.products.find({
  $and: [
    { price: { $gte: 100 } },
    { price: { $lte: 500 } }
  ]
})

// $or — any condition can match
db.products.find({
  $or: [
    { category: "Electronics" },
    { price: { $lt: 50 } }
  ]
})

// $not — negate a condition
db.products.find({ price: { $not: { $gt: 500 } } })

// $exists — field exists or not
db.users.find({ phone: { $exists: true } })

// $regex — pattern matching
db.users.find({ name: { $regex: /^A/i } })  // starts with A