Beginner MongoDB

MongoDB Query Operators ($eq, $gt, $in, etc.)

Explore comparison, logical, and element query operators to build powerful filters.

7 min read Tutorial

Query Operators Overview

MongoDB query operators let you build expressive filters that go beyond simple equality checks. They fall into several categories: comparison, logical, element, and evaluation operators. These operators are used inside filter documents passed to methods like find(), updateMany(), and deleteMany().

Comparison Operators

Compare field values against specified values:

// $eq - Equal to (implicit in simple filters)
db.users.find({ age: { $eq: 25 } })

// $ne - Not equal to
db.users.find({ status: { $ne: "inactive" } })

// $gt / $gte - Greater than / Greater than or equal
db.products.find({ price: { $gt: 100 } })
db.products.find({ price: { $gte: 100 } })

// $lt / $lte - Less than / Less than or equal
db.products.find({ stock: { $lt: 10 } })

// Combine for ranges
db.products.find({ price: { $gte: 50, $lte: 200 } })

$in and $nin

Match against a list of possible values:

// $in - Match any value in the array
db.users.find({ role: { $in: ["admin", "moderator"] } })

// $nin - Match none of the values
db.products.find({
  category: { $nin: ["discontinued", "archived"] }
})

Logical Operators

Combine multiple conditions with logical operators:

// $and - All conditions must match (explicit form)
db.products.find({
  $and: [
    { price: { $gte: 50 } },
    { price: { $lte: 200 } },
    { inStock: true }
  ]
})

// $or - At least one condition must match
db.users.find({
  $or: [
    { role: "admin" },
    { permissions: "manage_users" }
  ]
})

// $not - Negate a condition
db.products.find({
  price: { $not: { $gt: 100 } }
})

// $nor - None of the conditions match
db.users.find({
  $nor: [
    { status: "banned" },
    { status: "suspended" }
  ]
})

Element Operators

Check for the existence or type of a field:

// $exists - Check if a field exists
db.users.find({ phoneNumber: { $exists: true } })
db.users.find({ deletedAt: { $exists: false } })

// $type - Match by BSON type
db.products.find({ price: { $type: "double" } })
db.mixed.find({ value: { $type: "string" } })

Evaluation Operators

Use regular expressions and expressions for advanced matching:

// $regex - Pattern matching
db.users.find({
  email: { $regex: /@gmail\.com$/, $options: "i" }
})

// $expr - Use aggregation expressions in queries
db.orders.find({
  $expr: { $gt: ["$total", "$budget"] }
})

Key Takeaways

  • Comparison operators ($gt, $lt, $in) filter by value ranges and sets.
  • Logical operators ($and, $or, $not) combine multiple conditions.
  • $exists and $type check field presence and BSON type.
  • $regex enables pattern matching; $expr allows cross-field comparisons.

Try this query in UnifySQL

Write, optimize, and collaborate on MongoDB queries with AI assistance.

Start Free