MongoDB Query Operators

Query operators in MongoDB are special keywords that help filter documents based on specific conditions. Instead of finding documents only by exact value matches, query operators allow comparisons, range checks, logical combinations, and much more. They are always written with a $ symbol at the beginning.

All examples use a products collection in a database called storeDB.

use storeDB

db.products.insertMany([
  { name: "Laptop", price: 55000, stock: 10, category: "Electronics", inStock: true },
  { name: "Headphones", price: 2500, stock: 50, category: "Electronics", inStock: true },
  { name: "Desk Chair", price: 8500, stock: 0, category: "Furniture", inStock: false },
  { name: "Notebook", price: 120, stock: 200, category: "Stationery", inStock: true },
  { name: "Monitor", price: 18000, stock: 5, category: "Electronics", inStock: true }
])

1. Comparison Operators

Comparison operators compare field values against a given value and return documents that satisfy the condition.

$eq — Equal To

db.products.find({ category: { $eq: "Electronics" } })

This returns all products where the category is exactly "Electronics." In most cases, writing { category: "Electronics" } achieves the same result. $eq is useful when building dynamic queries programmatically.

$ne — Not Equal To

db.products.find({ category: { $ne: "Furniture" } })

This returns all products where the category is not "Furniture."

$gt — Greater Than

db.products.find({ price: { $gt: 10000 } })

This returns all products with a price greater than 10,000. The result includes Laptop (55000) and Monitor (18000).

$gte — Greater Than or Equal To

db.products.find({ price: { $gte: 18000 } })

This returns products priced at 18,000 or more. Monitor (18000) and Laptop (55000) match.

$lt — Less Than

db.products.find({ price: { $lt: 3000 } })

This returns products priced below 3,000. Headphones (2500) and Notebook (120) match.

$lte — Less Than or Equal To

db.products.find({ stock: { $lte: 10 } })

This returns products with stock of 10 or fewer units.

$in — Match Any Value in a List

db.products.find({ category: { $in: ["Electronics", "Stationery"] } })

This returns products where the category is either "Electronics" or "Stationery." $in is similar to the SQL IN operator.

$nin — Not In a List

db.products.find({ category: { $nin: ["Furniture", "Stationery"] } })

This returns all products where the category is neither "Furniture" nor "Stationery."

2. Logical Operators

Logical operators combine multiple conditions together.

$and — All Conditions Must Match

db.products.find({
  $and: [
    { price: { $gt: 2000 } },
    { inStock: true }
  ]
})

This returns products that are both priced above 2,000 and available in stock.

Writing multiple conditions inside a single filter object also applies AND logic by default:

db.products.find({ price: { $gt: 2000 }, inStock: true })

$or — At Least One Condition Must Match

db.products.find({
  $or: [
    { price: { $lt: 200 } },
    { category: "Furniture" }
  ]
})

This returns products where the price is under 200 or the category is "Furniture."

$nor — None of the Conditions Should Match

db.products.find({
  $nor: [
    { category: "Furniture" },
    { inStock: false }
  ]
})

This returns products that are neither in the Furniture category nor out of stock.

$not — Negate a Condition

db.products.find({ price: { $not: { $gt: 10000 } } })

This returns products where the price is not greater than 10,000 — meaning products priced at 10,000 or below.

3. Element Operators

Element operators check the existence or type of a field in a document.

$exists — Check if a Field Exists

db.products.find({ discount: { $exists: true } })

This returns documents that have a discount field, regardless of its value. To find documents without a field:

db.products.find({ discount: { $exists: false } })

$type — Check the Data Type of a Field

db.products.find({ price: { $type: "double" } })

This returns products where the price field stores a double (decimal) value. Supported type names include "string", "int", "double", "bool", "date", "array", and "objectId".

4. Evaluation Operators

$regex — Pattern Matching in Strings

db.products.find({ name: { $regex: /^Mon/i } })

This returns products where the name starts with "Mon" (case-insensitive). The i flag makes the search ignore uppercase and lowercase differences. This query returns "Monitor."

db.products.find({ name: { $regex: "head", $options: "i" } })

This finds any product with "head" anywhere in the name. "Headphones" matches.

$expr — Compare Two Fields in the Same Document

db.products.find({ $expr: { $gt: ["$stock", "$price"] } })

This returns documents where the stock value is greater than the price value. Field names are prefixed with $ when referencing them inside expressions.

5. Array Operators

Array operators work specifically with fields that contain arrays.

$all — Array Contains All Given Values

db.orders.find({ tags: { $all: ["express", "gift"] } })

This returns orders where the tags array contains both "express" and "gift" (order does not matter).

$elemMatch — Match Documents Where an Array Element Satisfies Multiple Conditions

db.orders.find({
  items: {
    $elemMatch: { quantity: { $gte: 2 }, price: { $lt: 500 } }
  }
})

This returns orders where at least one item in the items array has a quantity of 2 or more and a price below 500 — both conditions on the same element.

$size — Match Arrays with a Specific Number of Elements

db.products.find({ tags: { $size: 3 } })

This returns documents where the tags array has exactly 3 elements.

Combining Operators — Real Example

Find all Electronics products that are in stock and priced between 2,000 and 20,000:

db.products.find({
  category: "Electronics",
  inStock: true,
  price: { $gte: 2000, $lte: 20000 }
})

This returns Headphones (2500) and Monitor (18000).

Quick Reference — Operator Summary

OperatorTypeMeaning
$eqComparisonEqual to
$neComparisonNot equal to
$gtComparisonGreater than
$gteComparisonGreater than or equal to
$ltComparisonLess than
$lteComparisonLess than or equal to
$inComparisonMatches any value in a list
$ninComparisonMatches none of the values in a list
$andLogicalAll conditions must match
$orLogicalAt least one condition must match
$norLogicalNone of the conditions should match
$notLogicalNegates a condition
$existsElementField exists or does not exist
$typeElementField has a specific data type
$regexEvaluationString matches a pattern
$allArrayArray contains all specified values
$elemMatchArrayArray element matches multiple conditions
$sizeArrayArray has a specific number of elements

Summary

MongoDB query operators provide fine-grained control over how documents are filtered. Comparison operators handle value ranges and matches. Logical operators combine conditions using AND, OR, NOR, and NOT. Element operators check field existence and type. Evaluation operators like $regex enable pattern matching. Array operators work with list-type fields. Combining these operators within a single query allows very precise data retrieval from any MongoDB collection.

Leave a Comment