OPTIONS

$and

$and

New in version 2.0.

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

$and performs a logical AND 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 to false, MongoDB will not evaluate the remaining expressions.

Consider the following example:

db.inventory.find({ $and: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )

This query will select all documents in the inventory collection where:

  • price field value equals 1.99 and
  • qty field value is less than 20 and
  • sale field value is equal to true.

MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. For example, you may write the above query as:

db.inventory.find( { price: 1.99, qty: { $lt: 20 } , sale: true } )

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:

db.inventory.update( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] }, { $set: { qty: 15 } } )

db.inventory.update( { price: { $ne: 1.99, $exists: true } } , { $set: { qty: 15 } } )

Both update() operations will set the value of the qty field in documents where:

  • the price field value does not equal 1.99 and
  • the price field exists.

See also

find(), update(), $ne, $exists, $set.

←   $or $not  →
ON THIS PAGE