Labs ICT
Pro Login

Logical Operators

Combining conditions with AND, OR, NOT.

Logical Operators

Logical operators are the glue that holds complex queries together. They let you combine multiple conditions to create precise filters for your data.

Think of logical operators as the decision-making tools in your query arsenal. They help you express "and," "or," "not," and "nor" conditions in a way that MongoDB understands.

The $and Operator

The $and operator requires all conditions to be true for a document to match. It's the most common logical operator and is used when you need to filter by multiple criteria simultaneously.

You can use $and explicitly, but MongoDB also supports implicit AND when you specify multiple conditions in a single query object. Both approaches work the same way.

db.users.find({ $and: [{ age: { $gte: 18 } }, { status: "active" }] })

db.products.find({ $and: [{ price: { $gt: 10 } }, { category: "electronics" }] })

db.users.find({ age: { $gte: 18 }, status: "active" })
Try it Yourself →

The $or Operator

The $or operator requires at least one condition to be true. It's perfect for queries where you want to match documents that satisfy any one of multiple criteria.

Use $or when you need to search across multiple fields or when you want to find documents that match any of several possible values.

db.users.find({ $or: [{ status: "active" }, { age: { $lt: 25 } }] })

db.products.find({ $or: [{ category: "books" }, { price: { $lt: 20 } }] })

db.orders.find({ $or: [{ status: "pending" }, { total: { $gt: 100 } }] })
Try it Yourself →

The $not and $nor Operators

The $not operator negates a condition. It's useful when you want to invert a query condition. $not can be used with any condition, including regular expressions.

The $nor operator requires all conditions to be false. It's like saying "find me documents that don't match any of these conditions." It's the opposite of $or.

db.users.find({ age: { $not: { $gte: 65 } } })

db.products.find({ $nor: [{ price: { $lt: 10 } }, { category: "clearance" }] })

db.users.find({ $nor: [{ status: "banned" }, { status: "deleted" }] })
Try it Yourself →