Evaluation Operators

Evaluation operators allow you to perform more complex queries using regular expressions, text search, and internal field comparisons.

1. $regex

Provides regular expression capabilities for pattern matching strings in queries.

// Find users whose name starts with "Jo" (case-insensitive)
db.users.find({ name: { $regex: /^Jo/i } })

// Find users whose email ends with "gmail.com"
db.users.find({ email: { $regex: /gmail.com$/ } })

2. $text

Performs text search on a collection that has a Text Index.

// First, create a text index
db.posts.createIndex({ content: "text" })

// Then, perform text search
db.posts.find({ $text: { $search: "mongodb tutorial" } })

3. $expr

Allows the use of aggregation expressions within the query language. This is extremely useful for comparing two fields in the same document.

// Find documents where spent is greater than budget
db.monthlyBudget.find({
  $expr: { $gt: ["$spent", "$budget"] }
})

4. $mod

Performs a modulo operation on the value of a field and selects documents with a specified result.

// Find items where quantity is even
db.inventory.find({ qty: { $mod: [2, 0] } })
Performance Warning: Regular expressions (especially non-anchored ones) can be slow. Use text indexes for large-scale string searching.