Guide to MongoDB Operators
Introduction
MongoDB provides a wide range of operators that enhance its querying, updating, and aggregation capabilities. These operators allow users to efficiently retrieve, manipulate, and analyze data stored in MongoDB collections. In this article, we will explore the three main categories of MongoDB operators:
- Query Operators – Used to filter and retrieve documents based on specific conditions.
- Update Operators – Modify existing documents within a collection.
- Aggregation Operators – Process and transform data using the powerful MongoDB Aggregation Framework.
Each section will cover the operators available in that category along with their syntax and example usage.
1. Query Operators in MongoDB
Query operators in MongoDB are used to filter documents based on specific conditions. These operators are applied in the find(), update(), and aggregate() queries. Below is a concise guide with syntax and examples for each category.
1.1 Comparison Operators
Used to compare values in a query.
$eq
(Equal to)
Syntax:
{ field: { $eq: value } }
Example: Find users whose age is exactly 25.
db.users.find({ age: { $eq: 25 } })
$ne
(Not Equal to)
Syntax:
{ field: { $ne: value } }
Example: Find users whose age is NOT 25.
db.users.find({ age: { $ne: 25 } })
$gt
(Greater than)
Syntax:
{ field: { $gt: value } }
Example: Find products with price greater than 100.
db.products.find({ price: { $gt: 100 } })
$gte
(Greater than or equal to)
Syntax:
{ field: { $gte: value } }
Example: Find employees with salary >= 5000.
db.employees.find({ salary: { $gte: 5000 } })
$lt
(Less than)
Syntax:
{ field: { $lt: value } }
Example: Find students with grades less than 60.
db.students.find({ grade: { $lt: 60 } })
$lte
(Less than or equal to)
Syntax:
{ field: { $lte: value } }
Example: Find houses priced ≤ 300,000.
db.houses.find({ price: { $lte: 300000 } })
$in
(Matches any value in an array)
Syntax:
{ field: { $in: [value1, value2, ...] } }
Example: Find users from the US, UK, or Canada.
db.users.find({ country: { $in: ["US", "UK", "Canada"] } })
$nin
(Does not match any value in an array)
Syntax:
{ field: { $nin: [value1, value2, ...] } }
Example: Find users not from the US or UK.
db.users.find({ country: { $nin: ["US", "UK"] } })
1.2 Logical Operators
Used to combine multiple conditions.
$and
(Both conditions must be true)
Syntax:
{ $and: [ { condition1 }, { condition2 } ] }
Example: Find employees with salary > 5000 AND age < 30.
db.employees.find({ $and: [ { salary: { $gt: 5000 } }, { age: { $lt: 30 } } ] })
$or
(At least one condition must be true)
Syntax:
{ $or: [ { condition1 }, { condition2 } ] }
Example: Find users from either New York OR Los Angeles.
db.users.find({ $or: [ { city: "New York" }, { city: "Los Angeles" } ] })
$nor
(None of the conditions must be true)
Syntax:
{ $nor: [ { condition1 }, { condition2 } ] }
Example: Find users who are NOT from New York or Los Angeles.
db.users.find({ $nor: [ { city: "New York" }, { city: "Los Angeles" } ] })
$not
(Negates a condition)
Syntax:
{ field: { $not: { operator: value } } }
Example: Find users whose age is NOT greater than 30.
db.users.find({ age: { $not: { $gt: 30 } } })
1.3 Element Operators
Used to check the existence and type of a field.
$exists
(Check if a field exists)
Syntax:
{ field: { $exists: true/false } }
Example: Find documents where the email
field exists.
db.users.find({ email: { $exists: true } })
$type
(Check field data type)
Syntax:
{ field: { $type: "type" } }
Example: Find documents where age
is stored as a number.
db.users.find({ age: { $type: "number" } })
1.4 Evaluation Operators
Used for string matching and expressions.
$regex
(Pattern matching)
Syntax:
{ field: { $regex: "pattern", $options: "flags" } }
Example: Find users with names starting with "J".
db.users.find({ name: { $regex: "^J", $options: "i" } })
$mod
(Modulo operation)
Syntax:
{ field: { $mod: [divisor, remainder] } }
Example: Find numbers divisible by 5.
db.numbers.find({ value: { $mod: [5, 0] } })
$expr
(Use aggregation expressions in queries)
Syntax:
{ $expr: { expression } }
Example: Find employees where salary
is greater than bonus
.
db.employees.find({ $expr: { $gt: ["$salary", "$bonus"] } })
1.5 Array Operators
Used to query arrays.
$all
(Matches all elements in an array)
Syntax:
{ field: { $all: [value1, value2] } }
Example: Find users who have both "JavaScript" and "Python" skills.
db.users.find({ skills: { $all: ["JavaScript", "Python"] } })
$size
(Matches arrays of a specific length)
Syntax:
{ field: { $size: n } }
Example: Find users who have exactly 3 hobbies.
db.users.find({ hobbies: { $size: 3 } })
$elemMatch
(Matches at least one array element that satisfies multiple conditions)
Syntax:
{ field: { $elemMatch: { condition1, condition2 } } }
Example: Find students with at least one subject where the score is > 80 and subject is "Math".
db.students.find({ grades: { $elemMatch: { score: { $gt: 80 }, subject: "Math" } } })
2. Update Operators in MongoDB
Update operators in MongoDB modify documents during update operations such as updateOne(), updateMany(), and findOneAndUpdate(). These operators are used in the $set parameter of an update query.
2.1 Field Update Operators
Used to modify fields in a document.
$set
(Update or Add a Field)
Syntax:
{ $set: { field: value } }
Example: Update a user's name to "John Doe".
db.users.updateOne({ _id: 1 }, { $set: { name: "John Doe" } })
$unset
(Remove a Field)
Syntax:
{ $unset: { field: "" } }
Example: Remove the age
field from a document.
db.users.updateOne({ _id: 1 }, { $unset: { age: "" } })
$rename
(Rename a Field)
Syntax:
{ $rename: { oldField: "newField" } }
Example: Rename the field username
to user_name
.
db.users.updateOne({ _id: 1 }, { $rename: { username: "user_name" } })
$currentDate
(Set Field to Current Date or Timestamp)
Syntax:
{ $currentDate: { field: { $type: "date" } } }
Example: Set the lastUpdated
field to the current date.
db.users.updateOne({ _id: 1 }, { $currentDate: { lastUpdated: true } })
$inc
(Increment a Numeric Field by a Value)
Syntax:
{ $inc: { field: value } }
Example: Increase the score
field by 10.
db.users.updateOne({ _id: 1 }, { $inc: { score: 10 } })
$mul
(Multiply a Numeric Field by a Value)
Syntax:
{ $mul: { field: value } }
Example: Double the price
of a product.
db.products.updateOne({ _id: 1 }, { $mul: { price: 2 } })
2.2 Array Update Operators
Used to modify array fields.
$push
(Add an Element to an Array)
Syntax:
{ $push: { arrayField: value } }
Example: Add "Node.js" to the skills
array.
db.users.updateOne({ _id: 1 }, { $push: { skills: "Node.js" } })
$pop
(Remove First or Last Element from an Array)
Syntax:
{ $pop: { arrayField: 1 } } // Removes last element
{ $pop: { arrayField: -1 } } // Removes first element
Example: Remove the last item from the tasks
array.
db.users.updateOne({ _id: 1 }, { $pop: { tasks: 1 } })
$pull
(Remove Elements Matching a Condition from an Array)
Syntax:
{ $pull: { arrayField: condition } }
Example: Remove all instances of "React" from the skills
array.
db.users.updateOne({ _id: 1 }, { $pull: { skills: "React" } })
$pullAll
(Remove Multiple Specific Values from an Array)
Syntax:
{ $pullAll: { arrayField: [value1, value2] } }
Example: Remove both "JavaScript" and "Python" from the skills
array.
db.users.updateOne({ _id: 1 }, { $pullAll: { skills: ["JavaScript", "Python"] } })
$addToSet
(Add an Element to an Array If It Doesn't Already Exist)
Syntax:
{ $addToSet: { arrayField: value } }
Example: Add "Java" to the skills
array only if it's not already present.
db.users.updateOne({ _id: 1 }, { $addToSet: { skills: "Java" } })
$each
(Push Multiple Elements at Once with $push
)
Syntax:
{ $push: { arrayField: { $each: [value1, value2] } } }
Example: Add "Vue.js" and "Angular" to the skills
array.
db.users.updateOne({ _id: 1 }, { $push: { skills: { $each: ["Vue.js", "Angular"] } } })
2.3 Miscellaneous Update Operators
Used for conditional updates.
$min
(Only Update If the New Value is Less Than the Current One)
Syntax:
{ $min: { field: value } }
Example: Update price
only if the new value is lower.
db.products.updateOne({ _id: 1 }, { $min: { price: 50 } })
$max
(Only Update If the New Value is Greater Than the Current One)
Syntax:
{ $max: { field: value } }
Example: Update salary
only if the new value is higher.
db.employees.updateOne({ _id: 1 }, { $max: { salary: 8000 } })
3. Aggregation Operators in MongoDB
Aggregation operators in MongoDB are used within the Aggregation Framework to process and transform data. These operators help in filtering, grouping, sorting, and performing mathematical or string operations on documents.
3.1 Stage Operators
Used within an aggregation pipeline to process documents at different stages.
$match
(Filters Documents Based on Conditions)
Syntax:
{ $match: { field: value } }
Example: Select users where age
is greater than 25.
db.users.aggregate([{ $match: { age: { $gt: 25 } } }])
$group
(Groups Documents by a Field and Performs Aggregation)
Syntax:
{ $group: { _id: "$field", aggregatedField: { $operation: "$field" } } }
Example: Count the number of users per country.
db.users.aggregate([{ $group: { _id: "$country", total: { $sum: 1 } } }])
$project
(Selects and Reshapes Fields)
Syntax:
{ $project: { field1: 1, field2: 1, _id: 0 } }
Example: Include name
and email
, exclude _id
.
db.users.aggregate([{ $project: { name: 1, email: 1, _id: 0 } }])
$sort
(Sorts Documents by a Field in Ascending or Descending Order)
Syntax:
{ $sort: { field: 1 } } // Ascending
{ $sort: { field: -1 } } // Descending
Example: Sort products by price in descending order.
db.products.aggregate([{ $sort: { price: -1 } }])
$limit
(Limits the Number of Documents Returned)
Syntax:
{ $limit: number }
Example: Return only 5 documents.
db.users.aggregate([{ $limit: 5 }])
$skip
(Skips a Certain Number of Documents)
Syntax:
{ $skip: number }
Example: Skip the first 10 documents.
db.users.aggregate([{ $skip: 10 }])
$lookup
(Performs Left Outer Join with Another Collection)
Syntax:
{
$lookup: {
from: "collection2",
localField: "field1",
foreignField: "field2",
as: "newField"
}
}
Example: Join orders
with users
collection.
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userDetails"
}
}
])
$count
(Counts the Number of Documents After Previous Stages)
Syntax:
{ $count: "totalCount" }
Example: Count the number of users older than 30.
db.users.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $count: "totalUsers" }
])
3.2 Mathematical Operators
Used to perform arithmetic calculations.
$add
(Adds Values Together)
Syntax:
{ $add: [field1, field2] }
Example: Calculate total salary (baseSalary + bonus
).
db.employees.aggregate([{ $project: { totalSalary: { $add: ["$baseSalary", "$bonus"] } } }])
$subtract
(Subtracts One Value from Another)
Syntax:
{ $subtract: [field1, field2] }
Example: Calculate years since joining.
db.employees.aggregate([{ $project: { yearsWorked: { $subtract: [2024, "$joinYear"] } } }])
Other Operators:
-
$multiply
→ Multiplies values. -
$divide
→ Divides values. -
$mod
→ Finds remainder. -
$pow
→ Raises a number to a power. -
$sqrt
→ Calculates square root. -
$trunc
→ Truncates decimal values.
3.3 Array Operators
Used for working with arrays.
$arrayElemAt
(Returns an Element at a Specified Index)
Syntax:
{ $arrayElemAt: ["$arrayField", index] }
Example: Get the first item in the tags
array.
db.products.aggregate([{ $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }])
Other Operators:
-
$arrayToObject
→ Converts an array to an object. -
$objectToArray
→ Converts an object to an array. -
$size
→ Returns the number of elements in an array. -
$reverseArray
→ Reverses an array.
3.4 String Operators
Used for manipulating strings.
$concat
(Concatenates Strings)
Syntax:
{ $concat: ["$field1", " ", "$field2"] }
Example: Combine first and last names.
db.users.aggregate([{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }])
Other Operators:
-
$substr
→ Extracts a substring. -
$toLower
→ Converts to lowercase. -
$toUpper
→ Converts to uppercase. -
$strLenCP
→ Returns string length.
3.5 Conditional Operators
Used for conditional evaluations.
$cond
(If-Else Condition)
Syntax:
{ $cond: { if: condition, then: value1, else: value2 } }
Example: Mark students as "Pass" or "Fail" based on score.
db.students.aggregate([{
$project: { status: { $cond: { if: { $gte: ["$score", 50] }, then: "Pass", else: "Fail" } } }
}])
3.6 Logical, Comparison & Aggregation Operators
Logical Operators
Used for logical conditions inside aggregation.
-
$and
→ Returns true if all conditions are met. -
$or
→ Returns true if at least one condition is met. -
$not
→ Negates a condition. -
$nor
→ Returns true if all conditions fail.
Comparison Operators
Used for value comparisons.
-
$eq
→ Checks if two values are equal. -
$ne
→ Checks if two values are not equal. -
$gt
,$gte
,$lt
,$lte
→ Greater than/Less than comparisons.
Aggregation Functions
Used to perform calculations on grouped data.
-
$sum
→ Calculates total. -
$avg
→ Calculates average. -
$min
,$max
→ Finds min/max value.
Example: Find average salary per department.
db.employees.aggregate([
{ $group: { _id: "$department", avgSalary: { $avg: "$salary" } } }
])
Conclusion
MongoDB operators provide a powerful way to query, update, and aggregate data efficiently. By leveraging query operators, developers can retrieve relevant documents based on precise conditions. Update operators allow modification of existing records, making it easy to maintain and update data dynamically. Aggregation operators enable complex data processing, allowing users to perform calculations, transformations, and analyses within the database itself.
Understanding these operators is essential for working effectively with MongoDB, whether you are building simple applications or handling large-scale data processing. By mastering MongoDB operators, developers can optimize performance, improve data retrieval, and enhance overall database efficiency.
Top comments (0)