This chapter introduces the logical operators of MongoDB, similar to the "and" and "or" conditions in SQL.

Logical Operators Supported by MongoDB

Operator Description
$and Matches documents that satisfy all the specified conditions, similar to the "and" condition in SQL
$not Performs a logical NOT operation on the specified expression
$or Matches documents that satisfy at least one of the specified conditions, similar to the "or" condition in SQL
$nor Matches documents that fail to satisfy both specified conditions

$and

Syntax:

{ $and: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Explanation:

  • is a sub-expression
  • $and takes an array containing a group of sub-expressions, and all sub-expressions must be satisfied

Example:

db.inventory.find( { $and: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } }] } )

Equivalent SQL:

select * from inventory where qty > 50 and qty < 10

$not

db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

Explanation:

  • If the condition is price > 1.99, then the NOT operation would be price <= 1.99.
  • This means querying for documents where price is less than or equal to 1.99 or where the price field does not exist.

Similar to SQL:

select * from inventory where price <= 1.99

$or

Similar to the "or" condition in SQL Syntax:

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Explanation:

  • is a sub-expression
  • $or takes an array containing a group of sub-expressions, and at least one sub-expression must be satisfied

Example:

db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

Equivalent SQL:

select * from inventory where quantity < 20 or price=10

$nor

Logical NOR operation Syntax:

{ $nor: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Example:

db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ]  } )

Explanation:

  • price != 1.99 and sale != true, or
  • price != 1.99 and the sale field is not present, or
  • the price field is not present and sale != true