Tutorials Logic, IN info@tutorialslogic.com

MongoDB Query Operators $eq, $gt, $in, $: Tutorial, Examples, FAQs & Interview Tips

MongoDB Query Operators $eq, $gt, $in, $

MongoDB in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

What are Query Operators?

Query operators let you build powerful filters to match documents based on conditions. They are prefixed with $ and are used inside the filter argument of find(), updateOne(), deleteMany(), and other methods.

Comparison Operators

$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin

$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
// $eq - equal to (same as { age: 29 })
db.users.find({ age: { $eq: 29 } })

// $ne - not equal to
db.users.find({ role: { $ne: "admin" } })

// $gt / $gte - greater than / greater than or equal
db.users.find({ age: { $gt: 25 } })
db.users.find({ age: { $gte: 18 } })

// $lt / $lte - less than / less than or equal
db.users.find({ age: { $lt: 65 } })
db.users.find({ score: { $lte: 100 } })

// Range query - age between 20 and 40
db.users.find({ age: { $gte: 20, $lte: 40 } })

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

// $nin - matches none of the values in the array
db.users.find({ status: { $nin: ["banned", "suspended"] } })

Logical Operators

$and, $or, $not, $nor

$and, $or, $not, $nor
// $and - all conditions must be true
db.users.find({
  $and: [
    { age: { $gte: 18 } },
    { active: true },
    { role: "user" }
  ]
})

// $or - at least one condition must be true
db.users.find({
  $or: [
    { role: "admin" },
    { age: { $gt: 50 } }
  ]
})

// $not - inverts the condition
db.users.find({ age: { $not: { $gt: 30 } } })

// $nor - none of the conditions must be true
db.users.find({
  $nor: [
    { role: "banned" },
    { active: false }
  ]
})

// Combining $and and $or
db.users.find({
  $and: [
    { active: true },
    { $or: [{ role: "admin" }, { role: "editor" }] }
  ]
})

Element Operators

$exists and $type

$exists and $type
// $exists - field exists (true) or does not exist (false)
db.users.find({ phone: { $exists: true } })
db.users.find({ deletedAt: { $exists: false } })

// $exists with a value check
db.users.find({ phone: { $exists: true, $ne: null } })

// $type - field matches a specific BSON type
db.users.find({ age: { $type: "int" } })
db.users.find({ age: { $type: "double" } })
db.users.find({ name: { $type: "string" } })
db.users.find({ tags: { $type: "array" } })

// Multiple types
db.users.find({ score: { $type: ["int", "double"] } })

Evaluation and Array Operators

$regex, $expr, $all, $elemMatch, $size

$regex, $expr, $all, $elemMatch, $size
// $regex - match a regular expression pattern
db.users.find({ name: { $regex: /^alice/i } })
db.users.find({ email: { $regex: "@gmail\\.com$" } })

// $expr - use aggregation expressions in queries
// Find users where their score is greater than their target
db.users.find({ $expr: { $gt: ["$score", "$target"] } })

// $all - array contains all specified values
db.products.find({ tags: { $all: ["mongodb", "database"] } })

// $elemMatch - at least one array element matches all conditions
db.orders.find({
  items: {
    $elemMatch: { product: "Laptop", qty: { $gte: 2 } }
  }
})

// $size - array has exactly N elements
db.users.find({ hobbies: { $size: 3 } })

Query Operators Quick Reference

Query Operators Quick Reference
// Comparison:  $eq $ne $gt $gte $lt $lte $in $nin
// Logical:     $and $or $not $nor
// Element:     $exists $type
// Evaluation:  $regex $expr $where $mod $text
// Array:       $all $elemMatch $size
// Bitwise:     $bitsAllClear $bitsAllSet $bitsAnyClear $bitsAnySet

// Real-world example: find active premium users aged 25-45
// who have at least one order and a verified email
db.users.find({
  active: true,
  plan: "premium",
  age: { $gte: 25, $lte: 45 },
  orderCount: { $gte: 1 },
  emailVerified: { $exists: true, $eq: true }
})

Applied guide for MongoDB

Use MongoDB when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why MongoDB is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.

  • Identify the exact problem solved by MongoDB.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.
Key Takeaways
  • I can explain where MongoDB fits inside a product catalog or user activity store.
  • I can point to the exact document shape and index affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small collection query that demonstrates MongoDB in a product catalog or user activity store.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.

Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.

Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.