DEV Community

SOVANNARO
SOVANNARO

Posted on

Understanding MongoDB Operators with Example Easy Understand

MongoDB provides a wide range of operators to perform queries, updates, and data manipulation operations. These operators help you filter, transform, and retrieve data efficiently. In this guide, we'll break down MongoDB operators and provide examples for easy understanding.


Types of MongoDB Operators

MongoDB operators can be categorized into the following types:

  1. Comparison Operators
  2. Logical Operators
  3. Element Operators
  4. Array Operators
  5. Update Operators
  6. Aggregation Pipeline Operators

Let's dive into each category with clear examples.


1. Comparison Operators

Comparison operators are used to filter documents based on specific conditions.

Common Comparison Operators:

  • $eq: Matches values equal to a specified value.
  • $ne: Matches values not equal to a specified value.
  • $gt: Matches values greater than a specified value.
  • $lt: Matches values less than a specified value.
  • $gte: Matches values greater than or equal to a specified value.
  • $lte: Matches values less than or equal to a specified value.
  • $in: Matches any of the values specified in an array.
  • $nin: Matches none of the values specified in an array.

Example Query:

Find all products with a price greater than 50:

// Products Collection
{
  "_id": 1, "name": "Product A", "price": 45
}
{
  "_id": 2, "name": "Product B", "price": 60
}

// Query
db.products.find({ "price": { "$gt": 50 } })
Enter fullscreen mode Exit fullscreen mode

Result:

[{ "_id": 2, "name": "Product B", "price": 60 }]
Enter fullscreen mode Exit fullscreen mode

2. Logical Operators

Logical operators combine multiple conditions.

Common Logical Operators:

  • $and: Matches documents that satisfy all specified conditions.
  • $or: Matches documents that satisfy at least one condition.
  • $not: Inverts the effect of a condition.
  • $nor: Matches documents that fail all conditions.

Example Query:

Find all products priced greater than 50 or named "Product A":

// Query
db.products.find({
  "$or": [
    { "price": { "$gt": 50 } },
    { "name": "Product A" }
  ]
})
Enter fullscreen mode Exit fullscreen mode

Result:

[
  { "_id": 1, "name": "Product A", "price": 45 },
  { "_id": 2, "name": "Product B", "price": 60 }
]
Enter fullscreen mode Exit fullscreen mode

3. Element Operators

These operators are used to match documents based on the existence or type of fields.

Common Element Operators:

  • $exists: Matches documents that have or do not have a specified field.
  • $type: Matches documents where the field is of a specified type.

Example Query:

Find documents where the "price" field exists:

// Query
db.products.find({ "price": { "$exists": true } })
Enter fullscreen mode Exit fullscreen mode

4. Array Operators

Array operators allow you to work with documents containing arrays.

Common Array Operators:

  • $all: Matches arrays that contain all specified elements.
  • $elemMatch: Matches arrays containing elements that satisfy all specified conditions.
  • $size: Matches arrays with a specific number of elements.

Example Query:

Find documents where the "tags" array contains exactly 3 elements:

// Products Collection
{
  "_id": 1, "tags": ["electronics", "sale", "new"]
}

// Query
db.products.find({ "tags": { "$size": 3 } })
Enter fullscreen mode Exit fullscreen mode

5. Update Operators

Update operators modify existing documents.

Common Update Operators:

  • $set: Sets the value of a field.
  • $unset: Removes a field from the document.
  • $inc: Increments the value of a field by a specified amount.
  • $push: Appends a value to an array.
  • $pull: Removes elements from an array that match a condition.

Example Update:

Increase the price of "Product A" by 10:

// Update Query
db.products.updateOne(
  { "name": "Product A" },
  { "$inc": { "price": 10 } }
)
Enter fullscreen mode Exit fullscreen mode

Result:

{ "_id": 1, "name": "Product A", "price": 55 }
Enter fullscreen mode Exit fullscreen mode

6. Aggregation Pipeline Operators

Aggregation operators are used to process and transform data within an aggregation pipeline.

Common Aggregation Operators:

  • $match: Filters documents.
  • $group: Groups documents by a specified field.
  • $sort: Sorts documents.
  • $project: Reshapes documents by including or excluding fields.
  • $limit: Limits the number of documents.

Example Aggregation:

Group products by price and count the number of products in each group:

// Aggregation Pipeline
db.products.aggregate([
  { "$group": { "_id": "$price", "count": { "$sum": 1 } } }
])
Enter fullscreen mode Exit fullscreen mode

Summary Table of Key MongoDB Operators

Operator Type Common Operators Description
Comparison $eq, $gt, $in, $lt Filter documents by conditions
Logical $and, $or, $not Combine multiple query conditions
Element $exists, $type Match documents by field existence or type
Array $all, $elemMatch, $size Handle arrays within documents
Update $set, $inc, $unset Modify document fields
Aggregation $match, $group, $sort Process data with pipelines

Conclusion

MongoDB operators are powerful tools that enable flexible and efficient querying, updating, and transforming of data. By understanding and using these operators correctly, you can unlock the full potential of MongoDB and build robust, scalable applications.

Top comments (0)