Learn MongoDB Evaluation Operators

MongoDB provides evaluation operators to perform complex query operations, such as regular expression matching and JavaScript-based evaluations. These operators allow for dynamic data retrieval and manipulation beyond simple comparisons.

Below are the most commonly used evaluation operators in MongoDB:

1. $regex – Regular Expression

The $regex operator is used to perform pattern matching within string fields using regular expressions. This is useful for filtering documents based on partial-string matches.

Example. Find all users whose name starts with "r".

db.users.find({
  name: { $regex: /^r/ }
})

O/P

Regular Expression

Note. This is a case-sensitive operator, so searching for a name with 'R' will not return any results if the name starts with a lowercase 'r'.

2. $mod – Modulus

The $mod operator performs a modulus operation on a field's value, returning documents where the result matches a specified value. It is helpful for filtering based on numerical patterns.

Example. Find users whose age is divisible by 5.

db.users.find({
    age: {
        $mod: [5, 0]
    }
})

O/P

Modulus

3. $expr – Expression Evaluation

The $expr operator allows for the evaluation of expressions within queries, enabling comparisons between fields within the same document.

Example. Find users where the value of age is greater than years of experience.

db.users.find({
  $expr: {
    $gt: ["$age", "$yearsOfExperience"]
  }
})

O/P

Expression Evaluation

4. $where – JavaScript-Based Query

The $where operator allows you to use JavaScript expressions to evaluate documents. This provides a high degree of flexibility but can be less efficient compared to other operators.

Example. Find users whose names are longer than 5.

db.users.find({ 
    $where: "this.name.length > 5" 
})

O/P

JavaScript

Conclusion

MongoDB's evaluation operators, such as $regex, $mod, $expr, and $where, provide advanced capabilities for querying data. These operators allow for more dynamic and flexible data retrieval, helping you perform complex matching, calculations, and evaluations.


Similar Articles