$and¶
-
$and
¶ New in version 2.0.
Syntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
$and
performs a logicalAND
operation on an array of two or more expressions (e.g.<expression1>
,<expression2>
, etc.) and selects the documents that satisfy all the expressions in the array. The$and
operator uses short-circuit evaluation. If the first expression (e.g.<expression1>
) evaluates tofalse
, MongoDB will not evaluate the remaining expressions.Consider the following example:
This query will select all documents in the
inventory
collection where:price
field value equals1.99
andqty
field value is less than20
andsale
field value is equal totrue
.
MongoDB provides an implicit
AND
operation when specifying a comma separated list of expressions. For example, you may write the above query as:If, however, a query requires an
AND
operation on the same field such as{ price: { $ne: 1.99 } } AND { price: { $exists: true } }
, then either use the$and
operator for the two separate expressions or combine the operator expressions for the field{ price: { $ne: 1.99, $exists: true } }
.Consider the following examples:
Both
update()
operations will set the value of theqty
field in documents where:- the
price
field value does not equal1.99
and - the
price
field exists.