Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs 菜单
Docs 主页
/ /

$and(查询谓词运算操作符)

$and

$and 对由一个或多个表达式组成的数组执行逻辑 AND 操作,并选择满足所有表达式的文档。

注意

指定用逗号分隔的表达式列表时,MongoDB 提供隐式 AND 操作。

可以使用 $and 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

  • MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本

  • MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本

$and 采用以下语法:

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

在评估 $and 表达式中的子句时,MongoDB 的查询优化器会考虑哪些可用索引在选择要执行的最佳计划时有助于满足 $and 表达式的子句。

要允许查询引擎优化查询,$and 会按如下方式处理错误:

  • 如果提供给 $and 的任何表达式在单独求值时会导致错误,则包含该表达式的 $and 可能但不一定会导致错误。

  • 在提供给 $and 的第一个表达式之后提供的表达式可能会导致错误,即使第一个表达式的计算结果为 false

例如,如果 $x0,以下查询会始终产生错误:

db.example.find( {
$expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] }
} )

以下查询包含提供给 $and 的多个表达式,如果存在 $x0 的任何文档,则查询可能会产生错误:

db.example.find( {
$and: [
{ x: { $ne: 0 } },
{ $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
]
} )

大多数编程语言和驱动程序,包括MongoDB Shell (mongosh),都不允许在同一对象级别构造具有重复键的对象。示例,如果您指定 { $ne: "R", $ne: "PG" } 等条件,则第二个值将覆盖第一个值。

要确认多个条件,请使用显式 AND

db.movies.find( {
$and: [
{ genres: { $in: [ "News", "Talk-Show" ] } },
{ genres: { $in: [ "History", "Western" ] } }
]},
{ title: 1, genres: 1, year: 1 }
)

上一个查询会明确检查两个条件是否都满足:genres 数组必须至少包含来自每个 $in 值集中的一个值。

本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

$and 匹配同一字段上的多个表达式。

请考虑以下查询:

db.movies.find(
{ $and: [ { year: { $gte: 1960 } }, { year: { $lte: 1970 } }, { directors: "Martin Scorsese" } ] },
{ title: 1, directors: 1, year: 1 })

该查询选择 movies 集合中满足如下条件的所有文档:

  • year 为 1960 或更高版本 并且

  • year 为 1970 或更早版本 并且

  • directors(包括马丁·斯科塞斯)

它还对结果进行投影,使其仅包含 titledirectorsyear 字段。该查询返回以下文档:

[
{
"_id": "573a1395f29313caabce2f95",
"title": "The Big Shave",
"directors": [ "Martin Scorsese" ],
"year": 1968
},
{
"_id": "573a1396f29313caabce3889",
"title": "Who's That Knocking at My Door",
"directors": [ "Martin Scorsese" ],
"year": 1967
}
]

您可以通过将 year字段的操作符组合到单个查询对象中并使用隐式 AND 操作符来简化此查询:

db.movies.find(
{ year: { $gte:1960, $lte:1970 }, directors:'Martin Scorsese' },
{ title: 1, directors: 1, year: 1 })

请务必查看您的查询,确认其符合预期行为。使用之前的 genres示例:

db.movies.find( { genres: { $in: [ "News", "Talk-Show" ], $in: [ "History", "Western" ] } } )

要查找 genres 数组包含 NewsTalk-Show 以及 HistoryWestern 的文档,请使用 $in

db.movies.find( {
$and: [
{ genres: { $in: [ "News", "Talk-Show" ] } },
{ genres: { $in: [ "History", "Western" ] } }
]},
{ title: 1, genres: 1, year: 1 }
)

如果字段是数组(例如 directors: [ "Jack Conway", "Howard Hawks", "William A. Wellman" ]),并且您想检查文档是否包含多个值(而不是一个值),请使用 $all

db.movies.find( { directors: { $all: ['John Murray Anderson','Pèl Fejès'] } }, { title: 1, directors: 1, year: 1 })

之前的查询在语义上等同于 AND,但在查询数组字段时,$all 更为清晰。

与重复字段名称类似,相同的注意事项也适用于查询中使用的重复操作符。

后退

逻辑

在此页面上