Database
NoSQL
MongoDB
Operators
Evaluation Query Operators

Evaluation Query Operators in MongoDB

Introduction

Evaluation Query Operators in MongoDB are used to perform queries based on the value of fields and their comparison with other values or fields. These operators help in executing more complex queries by evaluating conditions and expressions. The primary evaluation operators include $expr, $jsonSchema, $mod, $regex, and $text.

$expr Operator

Description:
The $expr operator allows you to use aggregation expressions within the query language. This operator enables complex queries that involve fields and expressions evaluated within the query itself.

db.products.find({
  $expr: { $gt: ["$quantity", "$price"] }
});

$jsonSchema Operator

Description:
The $jsonSchema operator is used for schema validation. It allows you to specify a schema in JSON format to validate the structure and content of documents in a collection.

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      properties: {
        name: {
          bsonType: "string",
          description: "Name must be a string"
        },
        age: {
          bsonType: "int",
          description: "Age must be an integer"
        }
      }
    }
  }
});

$mod Operator

Description:
The $mod operator performs a modulo operation on a field and matches the results against the specified value. This is useful for queries where you need to find documents based on a mathematical condition.

db.numbers.find({
  number: { $mod: [5, 1] }
});

$regex Operator

Description:
The $regex operator allows you to perform pattern matching using regular expressions. This operator is used to find documents where the value of a field matches a specific pattern.

db.users.find({
  name: { $regex: "^John" }
});

$text Operator

Description:
The $text operator is used for text search in MongoDB. It performs a text search on string content within a field and is useful for full-text search operations.

db.articles.find({
  $text: { $search: "MongoDB" }
});

Conclusion

Evaluation Query Operators in MongoDB provide powerful ways to query documents based on field values and their evaluation. The $expr operator allows for complex queries involving expressions, while $jsonSchema ensures data validation according to a specified schema. The $mod operator handles mathematical conditions, $regex enables pattern matching, and $text supports full-text search. Utilizing these operators effectively can enhance the flexibility and precision of your queries.