$and (aggregation)

Definition

  • $and
  • Evaluates one or more expressions and returns true if all ofthe expressions are true or if evoked with no argumentexpressions. Otherwise, $and returns false.

$and has the following syntax:

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

For more information on expressions, seeExpressions.

Behavior

$and uses short-circuit logic: the operation stopsevaluation after encountering the first false expression.

In addition to the false boolean value, $and evaluatesas false the following: null, 0, and undefinedvalues. The $and evaluates all other values as true,including non-zero numeric values and arrays.

Example Result
{ $and: [ 1, "green" ] } true
{ $and: [ ] } true
{ $and: [ [ null ], [ false ], [ 0 ] ] } true
{ $and: [ null, true ] } false
{ $and: [ 0, true ] } false

Example

Create an example inventory collection with the following documents:

  1. db.inventory.insertMany([
  2. { "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },
  3. { "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },
  4. { "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },
  5. { "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },
  6. { "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
  7. ])

The following operation uses the $and operator todetermine if qty is greater than 100 and less than 250:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. item: 1,
  7. qty: 1,
  8. result: { $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] } ] }
  9. }
  10. }
  11. ]
  12. )

The operation returns the following results:

  1. { "_id" : 1, "item" : "abc1", "qty" : 300, "result" : false }
  2. { "_id" : 2, "item" : "abc2", "qty" : 200, "result" : true }
  3. { "_id" : 3, "item" : "xyz1", "qty" : 250, "result" : false }
  4. { "_id" : 4, "item" : "VWZ1", "qty" : 300, "result" : false }
  5. { "_id" : 5, "item" : "VWZ2", "qty" : 180, "result" : true }