On this page本页内容
$or
¶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>
. $or
运算符对两个或多个<expressions>
的数组执行逻辑or操作,并选择至少满足一个<expressions>
的文档。The $or
has the following syntax:$or
语法如下所示:
Consider the following example:考虑下面的例子:
This query will select all documents in the 此查询将选择inventory
collection where either the quantity
field value is less than 20
or the price
field value equals 10
.inventory
集合中quantity
字段值小于20
或price
字段值等于10的所有单据。
$or
When evaluating the clauses in the 在计算$or
expression, MongoDB either performs a collection scan or, if all the clauses are supported by indexes, MongoDB performs index scans. $or
表达式中的子句时,MongoDB要么执行集合扫描,要么在索引支持所有子句的情况下,MongoDB执行索引扫描。That is, for MongoDB to use indexes to evaluate an 也就是说,为了让MongoDB使用索引来计算$or
expression, all the clauses in the $or
expression must be supported by indexes. $or
表达式,必须使用索引来支持$or
表达式中的所有子句。Otherwise, MongoDB will perform a collection scan.否则,MongoDB将执行收集扫描。
When using indexes with 在将索引与$or
queries, each clause of an $or
can use its own index. $or
查询一起使用时,$or
的每个子句都可以使用自己的索引。Consider the following query:考虑下面的查询:
To support this query, rather than a compound index, you would create one index on 要支持此查询,而不是复合索引,您需要创建一个quantity
and another index on price
:quantity
索引和另一个price
索引:
MongoDB can use all but the geoHaystack index to support MongoDB可以使用geoHaystack索引以外的所有索引来支持$or
clauses.$or
子句。
$or
and text
Queries$or
和text
查询¶If 如果$or
includes a $text
query, all clauses in the $or
array must be supported by an index. $or
包含$text
查询,则$or
数组中的所有子句都必须由索引支持。This is because a 这是因为$text
query must use an index, and $or
can only use indexes if all its clauses are supported by indexes. $text
查询必须使用索引,而$or
只能在其所有子句都受索引支持的情况下使用索引。If the 如果$text
query cannot use an index, the query will return an error.$text
查询无法使用索引,则查询将返回错误。
$or
$or
supports geospatial clauses with the following exception for the near clause (near clause includes 支持地理空间子句,但near子句除外(near子句包括$nearSphere
and $near
). $nearSphere
和$near
)。$or
cannot contain a near clause with any other clause.$or
不能与任何其他子句一起包含near子句。
$or
When executing 当使用$or
queries with a sort()
, MongoDB can now use indexes that support the $or
clauses. sort()
执行$or
查询时,MongoDB现在可以使用支持$or
子句的索引。Previous versions did not use the indexes.以前的版本没有使用索引。
$or
versus $in
$or
与$in
的比较¶When using 当使用$or
with <expressions>
that are equality checks for the value of the same field, use the $in
operator instead of the $or
operator.$or
和<expressions>
对同一字段的值进行相等检查时,请使用$in
运算符,而不是$or
运算符。
For example, to select all documents in the 例如,要选择库存inventory
collection where the quantity
field value equals either 20
or 50
, use the $in
operator:中
quantity
字段值等于20
或50
的所有文档,请使用$in
运算符: