$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 logicalOR
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:
This query will select all documents in the
inventory
collection where:- the
price
field value equals1.99
and - either the
qty
field value is less than20
or thesale
field value istrue
.
Consider the following example which uses the
$or
operator to select fields from embedded documents:This
update()
operation will set the value of thesale
field in the documents in theinventory
collection where:- the
price
field value equals10.99
or - the
carrier
embedded document contains a fieldstate
whose value equalsNY
.
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 equals1.99
or thesale
field value equalstrue
, and - either
qty
field value equals20
orqty
field value equals50
,
The most effective query would be:
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: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
$or
operator with thesort()
method in a query, the query will not use the indexes on the$or
fields. Consider the following query which adds asort()
method to the above query:This modified query will not use the index on
price
nor the index onsale
.You cannot use the
$or
operator with2d
geospatial queries.
- the