MongoDB Logical Operators


Logical Operators in MongoDB

Logical operators in MongoDB are used to combine multiple query conditions to match documents that satisfy one or more criteria. These operators are essential for constructing complex queries and filtering data based on various conditions. Here’s an overview of the logical operators available in MongoDB:

1. $and

The $and operator is used to combine multiple query conditions, and a document must satisfy all of these conditions to be included in the result set.

Syntax:

db.collection.find({ $and: [ { condition1 }, { condition2 } ] })

Example: Find documents where the age is greater than 25 and the status is "active":

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

This query will return documents that meet both conditions.

2. $or

The $or operator is used to match documents that satisfy at least one of the specified conditions.

Syntax:

db.collection.find({ $or: [ { condition1 }, { condition2 } ] })

Example: Find documents where the status is either "active" or "pending":

db.orders.find({ $or: [ { status: "active" }, { status: "pending" } ] })

This query will return documents that match either condition.

3. $not

The $not operator is used to invert the query conditions, meaning it matches documents that do not satisfy the specified condition.

Syntax:

db.collection.find({ field: { $not: condition } })

Example: Find documents where the age is not greater than 30:

db.users.find({ age: { $not: { $gt: 30 } } })

This query will return documents where the age is less than or equal to 30.

4. $nor

The $nor operator is used to match documents that do not satisfy any of the specified conditions. It is effectively the opposite of $or.

Syntax:

db.collection.find({ $nor: [ { condition1 }, { condition2 } ] })

Example: Find documents where the status is neither "active" nor "pending":

db.orders.find({ $nor: [ { status: "active" }, { status: "pending" } ] })

This query will return documents where the status is neither "active" nor "pending".

5. $exists

The $exists operator is used to match documents based on the existence or non-existence of a field. It can be used with a boolean value (true or false).

Syntax:

db.collection.find({ field: { $exists: true } })

Example: Find documents where the email field exists:

db.users.find({ email: { $exists: true } })

To find documents where the email field does not exist:

db.users.find({ email: { $exists: false } })

Combining Logical Operators

You can combine logical operators to create more complex queries. For example, you can use $and to combine $or and $not conditions.

Example: Find documents where the age is greater than 25 and either the status is "active" or the email field does not exist:

db.users.find({ $and: [ { age: { $gt: 25 } }, { $or: [ { status: "active" }, { email: { $exists: false } } ] } ] })