$or¶
-
$or¶ New in version 1.6.
Changed in version 2.0: You may nest
$oroperations; however, these expressions are not as efficiently optimized as top-level.Syntax:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }The
$oroperator performs a logicalORoperation on an array of two or more<expressions>and selects the documents that satisfy at least one of the<expressions>.Consider the following query:
This query will select all documents in the
inventorycollection where:- the
pricefield value equals1.99and - either the
qtyfield value is less than20or thesalefield value istrue.
Consider the following example which uses the
$oroperator to select fields from embedded documents:This
update()operation will set the value of thesalefield in the documents in theinventorycollection where:- the
pricefield value equals10.99or - the
carrierembedded document contains a fieldstatewhose value equalsNY.
When using
$orwith<expressions>that are equality checks for the value of the same field, choose the$inoperator over the$oroperator.Consider the query to select all documents in the
inventorycollection where:- either
pricefield value equals1.99or thesalefield value equalstrue, and - either
qtyfield value equals20orqtyfield value equals50,
The most effective query would be:
Consider the following behaviors when using the
$oroperator:When using indexes with
$orqueries, remember that each clause of an$orquery can use its own index. Consider the following query:For this query, you would create one index on
price(db.inventory.ensureIndex( { price: 1 } )) and another index onsale(db.inventory.ensureIndex( { sale: 1 } )) rather than a compound index.Also, when using the
$oroperator with thesort()method in a query, the query will not use the indexes on the$orfields. Consider the following query which adds asort()method to the above query:This modified query will not use the index on
pricenor the index onsale.You cannot use the
$oroperator with2dgeospatial queries.
- the