MongoDB提供了不同类型的逻辑查询运算符,而$and
运算符就是其中之一。该运算符用于对一个或多个表达式的数组执行逻辑AND操作,并仅选择或检索与该数组中所有给定表达式匹配的那些文档。您可以根据需要在find()
, update()
等方法中使用此运算符。
- 该运算符进行短路评估。
- 如果$ and运算符的第一个表达式评估为false,则MongoDB将不评估数组中的其余表达式。
- 您也可以在逗号(,)的帮助下隐式使用AND操作。
- 当在多个表达式中指定相同的字段或运算符时,可以使用AND操作(即$ and)。
句法:
{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}
例子:
在以下示例中,我们正在使用:
Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.
使用$and
运算符匹配值:
在此示例中,我们仅检索分支机构为CSE且joinYear为2018年的那些雇员的文档。
db.contributor.find({$and: [{branch: "CSE"},
{joiningYear: 2018}]}).pretty()
将$and
运算符与指定同一字段的多个表达式一起使用:
在此示例中,我们仅检索分支机构为CSE的那些雇员的文档。
db.contributor.find({$and: [{branch: {$eq: "CSE"}},
{branch: {$exists: true}}]}).pretty()
或者
db.contributor.find({branch: {$eq: "CSE", $exists: true}}).pretty()
将$ and运算符与多个表达式指定相同的运算符:
在此示例中,我们仅检索那些满足给定条件的员工文件。
db.contributor.find({$and: [{$or: [{branch: "ECE"}, {joiningYear: 2017}]},
{$or: [{"personal.state": "UP"},
{"personal.age": 25}]}]}).pretty()