Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$isNumber(聚合)

在此页面上

  • 定义
  • 例子
$isNumber

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

$isNumber 返回:

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

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

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

{ $isNumber: <expression> }

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

提示

另请参阅:

examples.sensors 集合发出以下操作以填充测试数据:

db.getSiblingDB("examples").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" }

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,则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 }
← $isArray(聚合)

在此页面上