$and¶
-
$and¶ Syntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }$andperforms a logicalANDoperation 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
ANDoperation when specifying a comma separated list of expressions.
Behavior¶
To allow the query engine to optimize queries, $and handles
errors as follows:
- If any expression supplied to
$andwould cause an error when evaluated alone, the$andcontaining the expression may cause an error but an error is not guaranteed. - An expression supplied after the first expression supplied to
$andmay cause an error even if the first expression evaluates tofalse.
For example, the following query always produces an error if $x is
0:
The following query, which contains multiple expressions supplied to
$and, may produce an error if there is any document where $x
is 0:
Examples¶
AND Queries With Multiple Expressions Specifying the Same Field¶
Consider this query:
The query selects all documents in the inventory collection where:
- the
pricefield value is not equal to1.99and - the
pricefield exists.
The query can be rewritten with an implicit AND operation that
combines the operator expressions for the price field:
AND Queries With Multiple Expressions Specifying the Same Operator¶
Consider this query:
The query selects all documents where:
- the
qtyfield value is less than10or greater than50, and - the
salefield value is equal totrueor thepricefield value is less than5.
The query cannot use an implicit AND operation because it uses the
$or operator more than once.
See also