对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$isNumber(表达式操作符)

$isNumber

$isNumber 检查指定表达式是否解析为下列数字 BSON 类型之一:

$isNumber 返回:

  • true 如果表达式解析为数字。

  • false 如果表达式解析为任何其他 BSON 类型、null 或缺失字段。

$isNumber 采用以下运算符表达式语法:

{ $isNumber: <expression> }

参数可以是任何有效表达式。

提示

对 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" }

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 }
给本页内容打分

在此页面上