Lesson 14 +10 XP

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

OperatorMeaning
$andBoth queries must match
$orEither query can match
$norNeither query matches
$notThe 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

OperatorMeaning
$regexMatch with a regular expression
$textFull-text search
$whereJavaScript 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, $not combine conditions.
  • $regex, $text, $where evaluate field content.
  • Multiple fields in one query object are implicitly ANDed.