Docs Home → Develop Applications → MongoDB Manual
$and![](/docs/v5.3/assets/link.svg)
$and
Syntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
$and
performs a logicalAND
operation on an array of one or more expressions (<expression1>
,<expression2>
, and so on) and selects the documents that satisfy all the expressions.Note
MongoDB provides an implicit
AND
operation when specifying a comma separated list of expressions.
Behavior![](/docs/v5.3/assets/link.svg)
To allow the query engine to optimize queries, $and
handles
errors as follows:
If any expression supplied to
$and
would cause an error when evaluated alone, the$and
containing the expression may cause an error but an error is not guaranteed.An expression supplied after the first expression supplied to
$and
may cause an error even if the first expression evaluates tofalse
.
For example, the following query always produces an error if $x
is
0
:
db.example.find( { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } )
The following query, which contains multiple expressions supplied to
$and
, may produce an error if there is any document where $x
is 0
:
db.example.find( { $and: [ { x: { $ne: 0 } }, { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } ] } )
Examples![](/docs/v5.3/assets/link.svg)
AND
Queries With Multiple Expressions Specifying the Same Field![](/docs/v5.3/assets/link.svg)
Consider this query:
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
The query selects all documents in the inventory
collection where:
the
price
field value is not equal to1.99
andthe
price
field exists.
The query can be rewritten with an implicit AND
operation that
combines the operator expressions for the price
field:
db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
AND
Queries With Multiple Expressions Specifying the Same Operator![](/docs/v5.3/assets/link.svg)
Consider this query:
db.inventory.find( { $and: [ { $or: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } } ] }, { $or: [ { sale: true }, { price : { $lt : 5 } } ] } ] } )
The query selects all documents where:
the
qty
field value is less than10
or greater than50
, andthe
sale
field value is equal totrue
or theprice
field value is less than5
.
The query cannot use an implicit AND
operation because it uses the
$or
operator more than once.