$and

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

$and performs a logical AND operation on an arrayof one or more expressions (e.g. <expression1>,<expression2>, etc.) and selects the documents that satisfyall the expressions in the array. The $and operatoruses short-circuit evaluation. If the first expression(e.g. <expression1>) evaluates to false, MongoDB will notevaluate the remaining expressions.

Note

MongoDB provides an implicit AND operation when specifying acomma separated list of expressions. Using an explicit ANDwith the $and operator is necessary when the same fieldor operator has to be specified in multiple expressions.

Examples

AND Queries With Multiple Expressions Specifying the Same Field

Consider the following example:

  1. db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )

This query will select all documents in the inventorycollection where:

  • the price field value is not equal to 1.99 and
  • the price field exists.

This query can be also be constructed with an implicit ANDoperation by combining the operator expressions for the pricefield. For example, this query can be written as:

  1. db.inventory.find( { price: { $ne: 1.99, $exists: true } } )

AND Queries With Multiple Expressions Specifying the Same Operator

Consider the following example:

  1. db.inventory.find( {
  2. $and : [
  3. { $or : [ { price : 0.99 }, { price : 1.99 } ] },
  4. { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
  5. ]
  6. } )

This query will select all documents where:

  • the price field value equals 0.99 or 1.99, and
  • the sale field value is equal to true or the qtyfield value is less than 20.

This query cannot be constructed using an implicit AND operation,because it uses the $or operator more than once.

See also

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