$or

$or

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>.

请看下面的查询:

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

此查询将会选择 inventory 集合中符合以下条件的所有文档:

  • 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.

请参考选择 inventory 集合中符合以下条件的所有文档的查询:

  • 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,

最有效的查询为:

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 will execute in parallel. These clauses can each use their 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})
    

    这个修改后的查询将不使用关于 price 的索引,也不使用关于 sale 的索引。

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