发布于 2015-09-14 15:00:58 | 135 次阅读 | 评论: 0 | 来源: 网络整理
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:
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:
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:
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.