发布于 2015-09-14 15:00:58 | 135 次阅读 | 评论: 0 | 来源: 网络整理

$or

1.6 新版功能.

在 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 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})
    

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

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

也可以参考

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

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务