SyntaxStudy
Sign Up
MongoDB Comparison and Logical Operators
MongoDB Beginner 1 min read

Comparison and Logical Operators

MongoDB query operators are prefixed with a dollar sign and provide expressive filtering capabilities. Comparison operators include $eq (equal), $ne (not equal), $gt and $gte (greater than / greater than or equal), $lt and $lte (less than / less than or equal), and $in and $nin (value in / not in array). Logical operators combine multiple conditions: $and requires all conditions to match, $or requires at least one, $nor requires none, and $not negates a single condition. When you pass multiple fields in a plain filter object, MongoDB implicitly applies $and. Using explicit $and is necessary only when you need multiple conditions on the same field.
Example
// $eq — explicit equality (shorthand is just { age: 30 })
db.users.find({ age: { $eq: 30 } })

// $gte / $lte — range query
db.users.find({ age: { $gte: 18, $lte: 65 } })

// $in — match any value in a list
db.products.find({ category: { $in: ["electronics", "computers"] } })

// $nin — exclude values
db.products.find({ status: { $nin: ["discontinued", "archived"] } })

// $and — all conditions must match (explicit form)
db.orders.find({
  $and: [
    { total: { $gte: 100 } },
    { status: "shipped" }
  ]
})

// $or — at least one condition must match
db.users.find({
  $or: [
    { age: { $lt: 18 } },
    { age: { $gt: 65 } }
  ]
})

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

// Combined logical operators
db.orders.find({
  status: "pending",
  $or: [{ priority: "high" }, { total: { $gte: 1000 } }]
})