$or

  • $or
  • The $or operator performs a logical OR operation on anarray of two or more <expressions> and selects the documentsthat satisfy at least one of the <expressions>. The$or has the following syntax:
  1. { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Consider the following example:

  1. db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

This query will select all documents in the inventory collectionwhere either the quantity field value is less than 20 or theprice field value equals 10.

Behaviors

$or Clauses and Indexes

When evaluating the clauses in the $or expression, MongoDBeither performs a collection scan or, if all the clauses are supportedby indexes, MongoDB performs index scans. That is, for MongoDB to useindexes to evaluate an $or expression, all the clauses in the$or expression must be supported by indexes. Otherwise,MongoDB will perform a collection scan.

When using indexes with $or queries, each clause of an$or can use its own index. Consider the following query:

  1. db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

To support this query, rather than a compound index, you would createone index on quantity and another index on price:

  1. db.inventory.createIndex( { quantity: 1 } )
  2. db.inventory.createIndex( { price: 1 } )

MongoDB can use all but the geoHaystackindex to support $or clauses.

$or and text Queries

Changed in version 2.6.

If $or includes a $text query, all clauses in the$or array must be supported by an index. This is because a$text query must use an index, and $or can only useindexes if all its clauses are supported by indexes. If the$text query cannot use an index, the query will return anerror.

$or and GeoSpatial Queries

Changed in version 2.6.

$or supports geospatial clauses with the following exceptionfor the near clause (near clause includes $nearSphere and$near). $or cannot contain a near clause with anyother clause.

$or and Sort Operations

Changed in version 2.6.

When executing $or queries with a sort(),MongoDB can now use indexes that support the $or clauses.Previous versions did not use the indexes.

$or versus $in

When using $or with <expressions> that are equality checksfor the value of the same field, use the $in operator insteadof the $or operator.

For example, to select all documents in the inventory collectionwhere the quantity field value equals either 20 or 50, use the$in operator:

  1. db.inventory.find ( { quantity: { $in: [20, 50] } } )

Nested $or Clauses

You may nest $or operations.

See also

$and, find(),sort(), $in