MongoDB $and运算符
介绍
MongoDB提供了各种逻辑查询运算符。and运算符是其中之一。and运算符用于对一个或多个表达式的数组执行逻辑AND运算。用户可以根据需要在find()、update()等方法中使用此运算符。
用户还可以借助逗号(,)使用”AND操作”。$and运算符使用短路评估。当用户在多个表达式中指定相同的字段或运算符时,用户可以使用”$AND操作”。
例如,假设有两个表达式(e1和e2)。如果第一个表达式(e1)的求值结果为false,那么第二个表达式(e2)将不会被求值。
语法
{ $and: [ { Expression 1 }, { Expression 2 }, { Expression 3 }, ..., { Expression N } ] }
or
{ { Expression 1 }, { Expression 2 }, { Expression 3 },..., { Expression N }}
示例
在以下示例中,我们正在处理:
Database: JavaTpoint
Collection: Student
Document: Six documents that contain the details of the students
[
        {
                "std_name" : "Jack",
                "sex" : "Male",
                "class" : "VI",
                "age" : 11,
                "grd_point" : 33
        },
        {
                "std_name" : "Jenny",
                "sex" : "Female",
                "class" : "VI",
                "age" : 13,
                "grd_point" : 30
        },
        {
                "std_name" : "Thomas",
                "sex" : "Male",
                "class" : "V",
                "age" : 11,
                "grd_point" : 35.1257
        },
        {
                "std_name" : "Lassy",
                "sex" : "Female",
                "class" : "X",
                "age" : 17,
                "grd_point" : 36.2514
        },
        {
                "std_name" : "Mia",
                "sex" : "Female",
                "class" : "X",
                "age" : 19,
                "grd_point" : 35.5201
        }
       {
                "std_name" : "Mike,
                "sex" : "Male",
                "class" : "V",
                "age" : 16,
                "grd_point" : 35.5201
        }
]
使用$and运算符匹配两个条件值:
在这个示例中,我们只获取符合以下条件的学生文档:
- 学生的“班级”为VI。
 - 学生的“性别”为女性。
 
>db.student.find({$and: [{"sex" : "Female"}, {"class" : "VI"}]}).pretty();
SQL等价命令:
SELECT * 
FROM student 
WHERE sex = "Female" AND class = "VI";
输出

注意: find() 方法以非结构化的格式显示文档,因此它使用 pretty() 方法以格式化的方式显示结果。
使用 $and 运算符匹配多个条件值 :
在这个示例中,我们只获取满足以下条件的学生文档:
- 学生的 “Age” 是17岁。
 - 学生的 “Sex” 是女性。
 - 学生的 “Class” 是X。
 
>db.student.find({and: [{"sex" : "Female"}, {"grd_point" : {gte: 31 }}, {"class" : "X"}]}).pretty();
SQL等效命令:
SELECT * 
FROM student 
WHERE sex = "Female" AND grd_point >= 31 AND class = "X";
输出:

极客笔记