Loading lessons...
Logical and Evaluation Operators
Logical and Evaluation Operators
Besides comparisons, MongoDB has logical operators for combining conditions and evaluation operators for pattern matching.
Logical operators
| Operator | Meaning |
|---|---|
| $and | Both queries must match |
| $or | Either query can match |
| $nor | Neither query matches |
| $not | The query must NOT match |
// Category is News AND likes is greater than 1
db.posts.find({ $and: [ { category: "News" }, { likes: { $gt: 1 } } ] })
// Category is News OR category is Technology
db.posts.find({ $or: [ { category: "News" }, { category: "Technology" } ] })
// Neither News nor Technology
db.posts.find({ $nor: [ { category: "News" }, { category: "Technology" } ] })
Evaluation operators
| Operator | Meaning |
|---|---|
| $regex | Match with a regular expression |
| $text | Full-text search |
| $where | JavaScript expression that must be true |
// Titles starting with "Post"
db.posts.find({ title: { $regex: "^Post" } })
When $and is implicit
MongoDB combines fields on the same document implicitly. { category: "News", likes: { $gt: 1 } } already means both conditions must match - you usually only need $and for complex cases.
TL;DR
$and,$or,$nor,$notcombine conditions.$regex,$text,$whereevaluate field content.- Multiple fields in one query object are implicitly ANDed.