本文主要是介绍MongoDB聚合运算符:$isNumber,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 语法
- 举例
- 用`$isNumber`检查字段是否是数值类型
- 用`$isNumber`有条件的修改字段值
$isNumber
聚合运算符返回操作数是否是一个数值(Integer、Decimal、Double、Long),返回一个布尔值,如果是数值返回true,否则返回false
语法
{ $isNumber: <expression> }
举例
用$isNumber
检查字段是否是数值类型
使用下面的脚本创建sensors
集合:
db.sensors.insertMany([{ "_id" : 1, "reading" : NumberDecimal(26.0) },{ "_id" : 2, "reading" : NumberLong(25.0) },{ "_id" : 3, "reading" : NumberInt(24) },{ "_id" : 4, "reading" : 24.0 },{ "_id" : 5, "reading" : "24" },{ "_id" : 6, "reading" : [ NumberDecimal(26) ]}
])
下面的聚合使用$addFields
阶段添加下面两个字段:
isNumber
:表示reading
字段是否为数值类型type
:表示reading
的BSON类型
db.sensors.aggregate([{$addFields : {"isNumber" : { $isNumber : "$reading" },"hasType" : {$type : "$reading"}}
}])
聚合操作返回下面的结果:
{ "_id" : 1, "reading" : NumberDecimal("26.0000000000000"), "isNum " : true, "type" : "decimal" }
{ "_id" : 2, "reading" : NumberLong(25), "isNum " : true, "type" : "long" }
{ "_id" : 3, "reading" : 24, "isNum " : true, "type" : "int" }
{ "_id" : 4, "reading" : 24, "isNum " : true, "type" : "double" }
{ "_id" : 5, "reading" : "24", "isNum " : false, "type" : "string" }
{ "_id" : 6, "reading" : [ NumberDecimal("26.0000000000000") ], "isNum " : false, "type" : "array" }
用$isNumber
有条件的修改字段值
使用下面的脚本创建grades
集合,包含了学生成绩的数据,grade
字段可能是数值类型的分数或字符类型的级别:
db.getSiblingDB("examples").grades.insertMany([{"student_id" : 457864153,"class_id" : "M044","class_desc" : "Introduction to MongoDB 4.4","grade" : "A"},{"student_id" : 457864153,"class_id" : "M103","class_desc" : "Basic Cluster Administration","grade" : 3.0},{"student_id" : 978451637,"class_id" : "M320","class_desc" : "MongoDB Data Modeling","grade" : "C"},{"student_id" : 978451637,"class_id" : "M001","class_desc" : "MongoDB Basics","grade" : 4.0}
])
下面的聚合使用$addFields
阶段添加points
字段,包含了课程的成绩值。该阶段使用$cond
运算符根据$isNumber
的输出设置points
的值:
- 如果为 true,则成绩已包含数字分值。设定分数等于成绩。
- 如果为 false,则
Grades
包含字符串字母值。使用$switch
将字母等级转换为其等效的分数,并赋予points
。
然后,聚合管道使用$group
阶段对Student_id
进行分组并计算学生的平均GPA。
db.getSiblingDB("examples").grades.aggregate([{$addFields: {"points" : {$cond : {if : { $isNumber : "$grade" },then: "$grade" ,else: {$switch : {branches: [{ case: {$eq : ["$grade" , "A"]}, then : 4.0 },{ case: {$eq : ["$grade" , "B"]}, then : 3.0 },{ case: {$eq : ["$grade" , "C"]}, then : 2.0 },{ case: {$eq : ["$grade" , "D"]}, then : 1.0 },{ case: {$eq : ["$grade" , "F"]}, then : 0.0 }]}}}}}},{$group : {_id : "$student_id",GPA : {$avg : "$points"}}}
])
聚合管道为每个唯一的student_id
输出一份文档以及该学生的 GPA 平均绩点:
{ "_id" : 457864153, "GPA" : 3.5 }
{ "_id" : 978451637, "GPA" : 3 }
这篇关于MongoDB聚合运算符:$isNumber的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!