DEV Community

Harsh Mishra
Harsh Mishra

Posted on

MongoDB Operators: Beginners Guide

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:

  1. Query Operators – Used to filter and retrieve documents based on specific conditions.
  2. Update Operators – Modify existing documents within a collection.
  3. 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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users whose age is exactly 25.

db.users.find({ age: { $eq: 25 } })
Enter fullscreen mode Exit fullscreen mode

$ne (Not Equal to)

Syntax:

{ field: { $ne: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users whose age is NOT 25.

db.users.find({ age: { $ne: 25 } })
Enter fullscreen mode Exit fullscreen mode

$gt (Greater than)

Syntax:

{ field: { $gt: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Find products with price greater than 100.

db.products.find({ price: { $gt: 100 } })
Enter fullscreen mode Exit fullscreen mode

$gte (Greater than or equal to)

Syntax:

{ field: { $gte: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Find employees with salary >= 5000.

db.employees.find({ salary: { $gte: 5000 } })
Enter fullscreen mode Exit fullscreen mode

$lt (Less than)

Syntax:

{ field: { $lt: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Find students with grades less than 60.

db.students.find({ grade: { $lt: 60 } })
Enter fullscreen mode Exit fullscreen mode

$lte (Less than or equal to)

Syntax:

{ field: { $lte: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Find houses priced 300,000.

db.houses.find({ price: { $lte: 300000 } })
Enter fullscreen mode Exit fullscreen mode

$in (Matches any value in an array)

Syntax:

{ field: { $in: [value1, value2, ...] } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users from the US, UK, or Canada.

db.users.find({ country: { $in: ["US", "UK", "Canada"] } })
Enter fullscreen mode Exit fullscreen mode

$nin (Does not match any value in an array)

Syntax:

{ field: { $nin: [value1, value2, ...] } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users not from the US or UK.

db.users.find({ country: { $nin: ["US", "UK"] } })
Enter fullscreen mode Exit fullscreen mode

1.2 Logical Operators

Used to combine multiple conditions.

$and (Both conditions must be true)

Syntax:

{ $and: [ { condition1 }, { condition2 } ] }
Enter fullscreen mode Exit fullscreen mode

Example: Find employees with salary > 5000 AND age < 30.

db.employees.find({ $and: [ { salary: { $gt: 5000 } }, { age: { $lt: 30 } } ] })
Enter fullscreen mode Exit fullscreen mode

$or (At least one condition must be true)

Syntax:

{ $or: [ { condition1 }, { condition2 } ] }
Enter fullscreen mode Exit fullscreen mode

Example: Find users from either New York OR Los Angeles.

db.users.find({ $or: [ { city: "New York" }, { city: "Los Angeles" } ] })
Enter fullscreen mode Exit fullscreen mode

$nor (None of the conditions must be true)

Syntax:

{ $nor: [ { condition1 }, { condition2 } ] }
Enter fullscreen mode Exit fullscreen mode

Example: Find users who are NOT from New York or Los Angeles.

db.users.find({ $nor: [ { city: "New York" }, { city: "Los Angeles" } ] })
Enter fullscreen mode Exit fullscreen mode

$not (Negates a condition)

Syntax:

{ field: { $not: { operator: value } } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users whose age is NOT greater than 30.

db.users.find({ age: { $not: { $gt: 30 } } })
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Find documents where the email field exists.

db.users.find({ email: { $exists: true } })
Enter fullscreen mode Exit fullscreen mode

$type (Check field data type)

Syntax:

{ field: { $type: "type" } }
Enter fullscreen mode Exit fullscreen mode

Example: Find documents where age is stored as a number.

db.users.find({ age: { $type: "number" } })
Enter fullscreen mode Exit fullscreen mode

1.4 Evaluation Operators

Used for string matching and expressions.

$regex (Pattern matching)

Syntax:

{ field: { $regex: "pattern", $options: "flags" } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users with names starting with "J".

db.users.find({ name: { $regex: "^J", $options: "i" } })
Enter fullscreen mode Exit fullscreen mode

$mod (Modulo operation)

Syntax:

{ field: { $mod: [divisor, remainder] } }
Enter fullscreen mode Exit fullscreen mode

Example: Find numbers divisible by 5.

db.numbers.find({ value: { $mod: [5, 0] } })
Enter fullscreen mode Exit fullscreen mode

$expr (Use aggregation expressions in queries)

Syntax:

{ $expr: { expression } }
Enter fullscreen mode Exit fullscreen mode

Example: Find employees where salary is greater than bonus.

db.employees.find({ $expr: { $gt: ["$salary", "$bonus"] } })
Enter fullscreen mode Exit fullscreen mode

1.5 Array Operators

Used to query arrays.

$all (Matches all elements in an array)

Syntax:

{ field: { $all: [value1, value2] } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users who have both "JavaScript" and "Python" skills.

db.users.find({ skills: { $all: ["JavaScript", "Python"] } })
Enter fullscreen mode Exit fullscreen mode

$size (Matches arrays of a specific length)

Syntax:

{ field: { $size: n } }
Enter fullscreen mode Exit fullscreen mode

Example: Find users who have exactly 3 hobbies.

db.users.find({ hobbies: { $size: 3 } })
Enter fullscreen mode Exit fullscreen mode

$elemMatch (Matches at least one array element that satisfies multiple conditions)

Syntax:

{ field: { $elemMatch: { condition1, condition2 } } }
Enter fullscreen mode Exit fullscreen mode

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" } } })
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Update a user's name to "John Doe".

db.users.updateOne({ _id: 1 }, { $set: { name: "John Doe" } })
Enter fullscreen mode Exit fullscreen mode

$unset (Remove a Field)

Syntax:

{ $unset: { field: "" } }
Enter fullscreen mode Exit fullscreen mode

Example: Remove the age field from a document.

db.users.updateOne({ _id: 1 }, { $unset: { age: "" } })
Enter fullscreen mode Exit fullscreen mode

$rename (Rename a Field)

Syntax:

{ $rename: { oldField: "newField" } }
Enter fullscreen mode Exit fullscreen mode

Example: Rename the field username to user_name.

db.users.updateOne({ _id: 1 }, { $rename: { username: "user_name" } })
Enter fullscreen mode Exit fullscreen mode

$currentDate (Set Field to Current Date or Timestamp)

Syntax:

{ $currentDate: { field: { $type: "date" } } }
Enter fullscreen mode Exit fullscreen mode

Example: Set the lastUpdated field to the current date.

db.users.updateOne({ _id: 1 }, { $currentDate: { lastUpdated: true } })
Enter fullscreen mode Exit fullscreen mode

$inc (Increment a Numeric Field by a Value)

Syntax:

{ $inc: { field: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Increase the score field by 10.

db.users.updateOne({ _id: 1 }, { $inc: { score: 10 } })
Enter fullscreen mode Exit fullscreen mode

$mul (Multiply a Numeric Field by a Value)

Syntax:

{ $mul: { field: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Double the price of a product.

db.products.updateOne({ _id: 1 }, { $mul: { price: 2 } })
Enter fullscreen mode Exit fullscreen mode

2.2 Array Update Operators

Used to modify array fields.

$push (Add an Element to an Array)

Syntax:

{ $push: { arrayField: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Add "Node.js" to the skills array.

db.users.updateOne({ _id: 1 }, { $push: { skills: "Node.js" } })
Enter fullscreen mode Exit fullscreen mode

$pop (Remove First or Last Element from an Array)

Syntax:

{ $pop: { arrayField: 1 } }  // Removes last element  
{ $pop: { arrayField: -1 } } // Removes first element  
Enter fullscreen mode Exit fullscreen mode

Example: Remove the last item from the tasks array.

db.users.updateOne({ _id: 1 }, { $pop: { tasks: 1 } })
Enter fullscreen mode Exit fullscreen mode

$pull (Remove Elements Matching a Condition from an Array)

Syntax:

{ $pull: { arrayField: condition } }
Enter fullscreen mode Exit fullscreen mode

Example: Remove all instances of "React" from the skills array.

db.users.updateOne({ _id: 1 }, { $pull: { skills: "React" } })
Enter fullscreen mode Exit fullscreen mode

$pullAll (Remove Multiple Specific Values from an Array)

Syntax:

{ $pullAll: { arrayField: [value1, value2] } }
Enter fullscreen mode Exit fullscreen mode

Example: Remove both "JavaScript" and "Python" from the skills array.

db.users.updateOne({ _id: 1 }, { $pullAll: { skills: ["JavaScript", "Python"] } })
Enter fullscreen mode Exit fullscreen mode

$addToSet (Add an Element to an Array If It Doesn't Already Exist)

Syntax:

{ $addToSet: { arrayField: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Add "Java" to the skills array only if it's not already present.

db.users.updateOne({ _id: 1 }, { $addToSet: { skills: "Java" } })
Enter fullscreen mode Exit fullscreen mode

$each (Push Multiple Elements at Once with $push)

Syntax:

{ $push: { arrayField: { $each: [value1, value2] } } }
Enter fullscreen mode Exit fullscreen mode

Example: Add "Vue.js" and "Angular" to the skills array.

db.users.updateOne({ _id: 1 }, { $push: { skills: { $each: ["Vue.js", "Angular"] } } })
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Update price only if the new value is lower.

db.products.updateOne({ _id: 1 }, { $min: { price: 50 } })
Enter fullscreen mode Exit fullscreen mode

$max (Only Update If the New Value is Greater Than the Current One)

Syntax:

{ $max: { field: value } }
Enter fullscreen mode Exit fullscreen mode

Example: Update salary only if the new value is higher.

db.employees.updateOne({ _id: 1 }, { $max: { salary: 8000 } })
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Select users where age is greater than 25.

db.users.aggregate([{ $match: { age: { $gt: 25 } } }])
Enter fullscreen mode Exit fullscreen mode

$group (Groups Documents by a Field and Performs Aggregation)

Syntax:

{ $group: { _id: "$field", aggregatedField: { $operation: "$field" } } }
Enter fullscreen mode Exit fullscreen mode

Example: Count the number of users per country.

db.users.aggregate([{ $group: { _id: "$country", total: { $sum: 1 } } }])
Enter fullscreen mode Exit fullscreen mode

$project (Selects and Reshapes Fields)

Syntax:

{ $project: { field1: 1, field2: 1, _id: 0 } }
Enter fullscreen mode Exit fullscreen mode

Example: Include name and email, exclude _id.

db.users.aggregate([{ $project: { name: 1, email: 1, _id: 0 } }])
Enter fullscreen mode Exit fullscreen mode

$sort (Sorts Documents by a Field in Ascending or Descending Order)

Syntax:

{ $sort: { field: 1 } } // Ascending  
{ $sort: { field: -1 } } // Descending  
Enter fullscreen mode Exit fullscreen mode

Example: Sort products by price in descending order.

db.products.aggregate([{ $sort: { price: -1 } }])
Enter fullscreen mode Exit fullscreen mode

$limit (Limits the Number of Documents Returned)

Syntax:

{ $limit: number }
Enter fullscreen mode Exit fullscreen mode

Example: Return only 5 documents.

db.users.aggregate([{ $limit: 5 }])
Enter fullscreen mode Exit fullscreen mode

$skip (Skips a Certain Number of Documents)

Syntax:

{ $skip: number }
Enter fullscreen mode Exit fullscreen mode

Example: Skip the first 10 documents.

db.users.aggregate([{ $skip: 10 }])
Enter fullscreen mode Exit fullscreen mode

$lookup (Performs Left Outer Join with Another Collection)

Syntax:

{
  $lookup: {
    from: "collection2",
    localField: "field1",
    foreignField: "field2",
    as: "newField"
  }
}
Enter fullscreen mode Exit fullscreen mode

Example: Join orders with users collection.

db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userDetails"
    }
  }
])
Enter fullscreen mode Exit fullscreen mode

$count (Counts the Number of Documents After Previous Stages)

Syntax:

{ $count: "totalCount" }
Enter fullscreen mode Exit fullscreen mode

Example: Count the number of users older than 30.

db.users.aggregate([
  { $match: { age: { $gt: 30 } } },
  { $count: "totalUsers" }
])
Enter fullscreen mode Exit fullscreen mode

3.2 Mathematical Operators

Used to perform arithmetic calculations.

$add (Adds Values Together)

Syntax:

{ $add: [field1, field2] }
Enter fullscreen mode Exit fullscreen mode

Example: Calculate total salary (baseSalary + bonus).

db.employees.aggregate([{ $project: { totalSalary: { $add: ["$baseSalary", "$bonus"] } } }])
Enter fullscreen mode Exit fullscreen mode

$subtract (Subtracts One Value from Another)

Syntax:

{ $subtract: [field1, field2] }
Enter fullscreen mode Exit fullscreen mode

Example: Calculate years since joining.

db.employees.aggregate([{ $project: { yearsWorked: { $subtract: [2024, "$joinYear"] } } }])
Enter fullscreen mode Exit fullscreen mode

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] }
Enter fullscreen mode Exit fullscreen mode

Example: Get the first item in the tags array.

db.products.aggregate([{ $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }])
Enter fullscreen mode Exit fullscreen mode

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"] }
Enter fullscreen mode Exit fullscreen mode

Example: Combine first and last names.

db.users.aggregate([{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }])
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

Example: Mark students as "Pass" or "Fail" based on score.

db.students.aggregate([{ 
  $project: { status: { $cond: { if: { $gte: ["$score", 50] }, then: "Pass", else: "Fail" } } }
}])
Enter fullscreen mode Exit fullscreen mode

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" } } }
])
Enter fullscreen mode Exit fullscreen mode

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)