OPTIONS

$or

$or

New in version 1.6.

Changed in version 2.0: You may nest $or operations; however, these expressions are not as efficiently optimized as top-level.

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

The $or operator performs a logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions>.

Consider the following query:

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

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

  • the price field value equals 1.99 and
  • either the qty field value is less than 20 or the sale field value is true.

Consider the following example which uses the $or operator to select fields from embedded documents:

db.inventory.update( { $or: [ { price:10.99 }, { "carrier.state": "NY"} ] }, { $set: { sale: true } } )

This update() operation will set the value of the sale field in the documents in the inventory collection where:

  • the price field value equals 10.99 or
  • the carrier embedded document contains a field state whose value equals NY.

When using $or with <expressions> that are equality checks for the value of the same field, choose the $in operator over the $or operator.

Consider the query to select all documents in the inventory collection where:

  • either price field value equals 1.99 or the sale field value equals true, and
  • either qty field value equals 20 or qty field value equals 50,

The most effective query would be:

db.inventory.find ( { $or: [ { price: 1.99 }, { sale: true } ], qty: { $in: [20, 50] } } )

Consider the following behaviors when using the $or operator:

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

    db.inventory.find ( { $or: [ { price: 1.99 }, { sale: true } ] } )
    

    For this query, you would create one index on price ( db.inventory.ensureIndex( { price: 1 } ) ) and another index on sale ( db.inventory.ensureIndex( { sale: 1 } ) ) rather than a compound index.

  • Also, when using the $or operator with the sort() method in a query, the query will not use the indexes on the $or fields. Consider the following query which adds a sort() method to the above query:

    db.inventory.find ( { $or: [ { price: 1.99 }, { sale: true } ] } ).sort({item:1})
    

    This modified query will not use the index on price nor the index on sale.

  • You cannot use the $or operator with 2d geospatial queries.

See also

find(), update(), $set, $and, sort().

ON THIS PAGE