条件表达式运算符主要用于实现表达式之间的条件运算,主要包括了null条件判断、条件判断等
一、准备工作
初始化学生数据
db.scores.insertMany([
{ "_id" : 1, "name" : "张三", "eng" : 80, "math" : 70, "physics": 80 },
{ "_id" : 2, "name" : "李四", "eng" : 60, "math" : 90 },
{ "_id" : 3, "name" : "王五", "eng" : 90, "math" : 50, "physics": 70 }
])
二、单条件判断($cond)
语法:{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
或者 { $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
其中,
boolean-expression:代表的是条件表达式
true-case:代表的是条件表达式为true时执行的分支
false-case:代表的是条件表达式为false时执行的分支
例子:计算学生的数学成绩是否及格
db.scores.aggregate([
{
$project: {
"name": 1,
"math": 1,
"pass": {
$cond: {
if: { $gte: [ "$math", 60 ] },
then: "及格",
else: "不及格"
}
}
}
}
])
等效于:
db.scores.aggregate([
{
$project: {
"name": 1,
"math": 1,
"pass": {
$cond: [
{ $gte: [ "$math", 60 ] },
"及格",
"不及格"
]
}
}
}
])
聚合查询的结果如下:
{ "_id" : 1, "name" : "张三", "math" : 70, "pass" : "及格" }
{ "_id" : 2, "name" : "李四", "math" : 90, "pass" : "及格" }
{ "_id" : 3, "name" : "王五", "math" : 50, "pass" : "不及格" }
三、多条件判断($switch)
语法:
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}
其中,
case: <expression>:代表的是条件表达式
then: <expression>:代表的是条件表达式满足时执行的表达式
default: <expression>:代表的是所有的条件表达式都不满足的情况下执行的表达式
例子:计算学生的数学成绩的等级
A: 90分及以上
B: 80分及以上
C: 70分及以上
D: 60分及以上
E: 60分以下
db.scores.aggregate([
{
$project: {
"name": 1,
"math": 1,
"level": {
$switch: {
branches: [
{ case: { $gte: [ "$math", 90 ] }, then: "A" },
{ case: { $gte: [ "$math", 80 ] }, then: "B" },
{ case: { $gte: [ "$math", 70 ] }, then: "C" },
{ case: { $gte: [ "$math", 60 ] }, then: "D" },
],
default: "E"
}
}
}
}
])
聚合查询的结果如下:
{ "_id" : 1, "name" : "张三", "math" : 70, "level" : "C" }
{ "_id" : 2, "name" : "李四", "math" : 90, "level" : "A" }
{ "_id" : 3, "name" : "王五", "math" : 50, "level" : "E" }
四、Null判断($ifNull)
语法:
{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<replacement-expression-if-null>
]
}
其中,
<input-expression>:代表的是输入的表达式
<replacement-expression-if-null>:代表的是输入的表达式为Null的情况下替代的表达式
在4.4版本及更早的版本中,$ifNull 仅支持一个输入表达式,语法如下:
{
$ifNull: [
<input-expression>,
<replacement-expression-if-null>
]
}
例子:查找学生的物理成绩,如果成绩不存在,则显示为0
db.scores.aggregate([
{
$project: {
"name": 1,
"physics": {
$ifNull: [ "$physics", 0 ]
}
}
}
])
聚合查询的结果如下:
{ "_id" : 1, "name" : "张三", "physics" : 80 }
{ "_id" : 2, "name" : "李四", "physics" : 0 }
{ "_id" : 3, "name" : "王五", "physics" : 70 }