定义
$isNumber$isNumber检查指定的 表达式是否解析为以下数字BSON types之一:$isNumber返回:true如果表达式解析为数字。false如果表达式解析为任何其他 BSON 类型、null或缺失字段。
$isNumber采用以下运算符表达式语法:{ $isNumber: <expression> } 参数可以是任何有效表达式。
提示
$type (Aggregation)— 返回参数的 BSON 类型。$type (Query)- 根据 BSON 类型过滤字段。
例子
使用 $isNumber 检查字段是否为数字
对 examples.sensors 集合发出以下操作以填充测试数据:
db.getSiblingDB("examples").sensors.insertMany([ { "_id" : 1, "reading" : Decimal128("26.0") }, { "_id" : 2, "reading" : Long(25) }, { "_id" : 3, "reading" : Int32(24) }, { "_id" : 4, "reading" : 24.0 }, { "_id" : 5, "reading" : "24" }, { "_id" : 6, "reading" : [ Decimal128("26") ]} ])
下面的聚合使用 $addFields 聚合阶段为每个文档添加以下字段:
isNumber- 指示reading的值是整数、小数、double 还是长数。type— 指示reading的 BSON 类型。
db.sensors.aggregate([{ $addFields : { "isNumber" : { $isNumber : "$reading" }, "hasType" : {$type : "$reading"} } }])
该聚合操作返回以下结果:
{ "_id" : 1, "reading" : Decimal128("26.0000000000000"), "isNum " : true, "type" : "decimal" } { "_id" : 2, "reading" : Long(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" : [ Decimal128("26.0000000000000") ], "isNum " : false, "type" : "array" }
使用 $isNumber 有条件地修改字段
grades 集合包含有关学生成绩的数据。grade 字段可以存储字符串字母等级或数字分值。
db.getSiblingDB("examples").grades.insertMany([ { "student_id" : 457864153, "class_id" : "01", "class_desc" : "Algebra", "grade" : "A" }, { "student_id" : 457864153, "class_id" : "02", "class_desc" : "Chemistry", "grade" : 3.0 }, { "student_id" : 978451637, "class_id" : "03", "class_desc" : "Physics", "grade" : "C" }, { "student_id" : 978451637, "class_id" : "04", "class_desc" : "English", "grade" : 4.0 } ])
以下聚合使用 $addFields 阶段添加一个 points 字段,其中包含该课程的数字成绩值。该阶段使用 $cond 操作符根据 $isNumber 的输出设置 points 的值:
如果为
true,则grades已包含数字分值。将points设置为等于grades。如果
false,则grades包含字符串字母值。使用$switch将字母成绩转换为其等效分值并分配给points。
然后,聚合管道使用 $group 阶段对 student_id 进行分组,并计算学生的 average 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 }