Skip to main content

MongoDB Query Operators

Introduction

Query operators in MongoDB are special elements that you can use to specify complex search conditions. They allow you to filter documents in a collection based on specific criteria such as equality, ranges, arrays, and more. Whether you need to find documents with specific values, within certain ranges, or with particular elements in an array, MongoDB's query operators provide the tools you need.

In this tutorial, we'll explore the most important MongoDB query operators, how they work, and how to use them effectively in your applications.

Understanding Query Operators

MongoDB query operators are special keys in query documents that start with a dollar sign ($). These operators provide ways to locate data within the database beyond simple equality matches.

Query operators are divided into several categories:

  • Comparison Operators: Compare values ($eq, $gt, $lt, etc.)
  • Logical Operators: Combine multiple queries ($and, $or, etc.)
  • Element Operators: Check for presence or absence of fields ($exists, $type)
  • Array Operators: Query array fields ($in, $all, etc.)
  • Evaluation Operators: Perform specific evaluations ($regex, $mod, etc.)

Let's explore each category with practical examples.

Comparison Operators

Comparison operators allow you to find documents with fields that match specific values.

Common Comparison Operators

OperatorDescription
$eqMatches values equal to the specified value
$neMatches values not equal to the specified value
$gtMatches values greater than the specified value
$gteMatches values greater than or equal to the specified value
$ltMatches values less than the specified value
$lteMatches values less than or equal to the specified value
$inMatches any of the values in an array
$ninMatches none of the values in an array

Examples

Let's assume we have a collection of products:

js
// Sample document in the products collection
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "Laptop",
price: 999.99,
category: "Electronics",
stock: 15,
ratings: [4.5, 4.8, 3.9, 5.0]
}

Find products with a price greater than $500

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

Output:

{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"stock": 15,
"ratings": [4.5, 4.8, 3.9, 5.0]
}

Find products with low stock (less than or equal to 10)

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

Find products that belong to specific categories

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

Find products with a price between 100and100 and 1000

js
db.products.find({ 
price: {
$gte: 100,
$lte: 1000
}
})

Logical Operators

Logical operators allow you to create complex queries by combining multiple conditions.

Common Logical Operators

OperatorDescription
$andJoins query clauses with a logical AND
$orJoins query clauses with a logical OR
$notInverts the effect of a query expression
$norJoins query clauses with a logical NOR

Examples

Find expensive electronics (price > $500 AND category is "Electronics")

js
db.products.find({
$and: [
{ price: { $gt: 500 } },
{ category: "Electronics" }
]
})

You can also write this more concisely:

js
db.products.find({
price: { $gt: 500 },
category: "Electronics"
})

Find products that are either electronics OR have a rating of 5.0

js
db.products.find({
$or: [
{ category: "Electronics" },
{ ratings: 5.0 }
]
})

Find products that aren't in the "Clothing" category

js
db.products.find({
category: { $not: { $eq: "Clothing" } }
})

Element Operators

Element operators help you match documents based on the presence, absence, or type of fields.

Common Element Operators

OperatorDescription
$existsMatches documents with or without a specific field
$typeMatches documents where the field is of a specified BSON type

Examples

Find products that have a "discount" field

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

Find products where price is a decimal (double) type

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

Array Operators

Array operators provide special capabilities for querying arrays in documents.

Common Array Operators

OperatorDescription
$allMatches arrays containing all the specified elements
$elemMatchMatches documents containing an array field with at least one element that matches all criteria
$sizeMatches arrays with the specified number of elements

Examples

Find products that have both ratings 4.5 and 5.0

js
db.products.find({
ratings: { $all: [4.5, 5.0] }
})

Find products with exactly 4 ratings

js
db.products.find({
ratings: { $size: 4 }
})

Using $elemMatch with a more complex example

Let's assume we have a collection with documents containing review data:

js
// Sample document in the products collection with reviews
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "Laptop",
reviews: [
{ user: "user1", rating: 4.5, verified: true },
{ user: "user2", rating: 3.0, verified: false },
{ user: "user3", rating: 5.0, verified: true }
]
}

To find products with at least one verified review with a rating over 4:

js
db.products.find({
reviews: {
$elemMatch: {
rating: { $gt: 4 },
verified: true
}
}
})

Evaluation Operators

Evaluation operators perform special operations on fields to determine a match.

Common Evaluation Operators

OperatorDescription
$regexMatches documents where string fields match a regular expression
$modMatches documents where a field value divided by a divisor has a specified remainder
$textPerforms text search
$whereMatches documents that satisfy a JavaScript expression

Examples

Find products with names containing "phone" (case insensitive)

js
db.products.find({
name: { $regex: /phone/i }
})

Find products where stock divided by 5 has remainder 0 (i.e., stock is divisible by 5)

js
db.products.find({
stock: { $mod: [5, 0] }
})

Real-World Application Examples

E-commerce Product Filtering

Let's implement a realistic e-commerce product filtering system:

js
// Find electronics priced between $200-$600, in stock, with good ratings
db.products.find({
category: "Electronics",
price: { $gte: 200, $lte: 600 },
stock: { $gt: 0 },
"ratings.average": { $gte: 4.0 }
})

User Analytics Application

Imagine a user analytics system:

js
// Find active users who registered in the last 30 days and have more than 5 logins
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

db.users.find({
status: "active",
registrationDate: { $gte: thirtyDaysAgo },
loginCount: { $gt: 5 }
})

Content Management System

For a blog or content platform:

js
// Find published articles containing "MongoDB" in the title and at least 5 comments
db.articles.find({
status: "published",
title: { $regex: /MongoDB/i },
comments: { $size: { $gte: 5 } }
})

Combining Multiple Operators

MongoDB allows combining multiple operators for complex queries:

js
// Find products that are:
// - either electronics with price over $1000
// - or clothing items with a discount
db.products.find({
$or: [
{
category: "Electronics",
price: { $gt: 1000 }
},
{
category: "Clothing",
discount: { $exists: true }
}
]
})

Query Performance Considerations

When using query operators, keep these performance tips in mind:

  1. Create indexes for fields used frequently in queries
  2. Avoid using regexes without anchors (e.g., ^) as they cannot use indexes effectively
  3. Limit the result set size using .limit() when possible
  4. Use more specific conditions first in $or queries
  5. Monitor query performance using explain() method

Example using explain():

js
db.products.find({ price: { $gt: 500 } }).explain("executionStats")

Summary

MongoDB query operators provide powerful tools to filter and find documents based on complex criteria. We've covered:

  • Comparison operators like $eq, $gt, $lt for basic comparisons
  • Logical operators like $and, $or for combining conditions
  • Element operators like $exists, $type for checking field properties
  • Array operators like $all, $elemMatch for working with arrays
  • Evaluation operators like $regex for advanced evaluations

Using these operators effectively will help you build sophisticated queries that match exactly what you need from your MongoDB collections.

Additional Resources and Exercises

Further Reading

Practice Exercises

  1. Create a collection called movies with fields for title, year, genres (array), and rating.
  2. Write a query to find all movies from the 2000s (2000-2009) with a rating above 8.
  3. Find movies that are either comedies OR have "adventure" in their title.
  4. Find movies that have exactly 3 genres listed.
  5. Find movies released after 2015 that don't have the genre "Horror".

These exercises will help you practice combining various MongoDB query operators to create effective filtering queries.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)