MongoDB $abs 运算符
MongoDB $abs 运算符 介绍
MongoDB 提供了多种算术表达式运算符。$abs 运算符就是这些运算符之一。$abs 运算符用于返回代码中特定数字的绝对值。绝对值意味着无论数字是正数还是负数,它总是返回一个正值。
MongoDB $abs 运算符 语法
{ $abs: <number> }
要点:
- 如果数字为 null,则 $abs 运算符返回 null。
- 如果输入的值引用了缺失的字段,则 $abs 运算符返回 null。
- 如果数字是 NaN,则 $abs 运算符返回 NaN。
MongoDB $abs 运算符 例子
在以下示例中,我们正在使用
Database: Yiidian
Collection: student
Document: Six documents that contain the details of the students
{
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d65f"),
"std_name" : "Micky",
"gender" : "Female",
"class" : "X",
"fees" : 5000,
"exam_fees" : 500,
"age" : 16,
"Total_marks" : 405
"Result" : "Pass"
},
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds34563"),
"std_name" : "Moty",
"gender" : "Male",
"fees" : 4000,
"exam_fees" : 500,
"class" : "VII",
"age" : 15,
"Total_marks" : 705
"Result" : "Pass"
},
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds31478"),
"std_name" : "Thomas",
"gender" : "Male",
"fees" : 3000,
"exam_fees" : 500,
"class" : "V",
"age" : 12,
" Total_marks" : 450
" Result" : "pass"
},
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds37832"),
"std_name" : "Jin",
"gender" : "Female",
"fees" : 5000,
"exam_fees" : 500,
"class" : "X",
"age" : 16,
"Total_marks" : 750
"Result" : "Pass"
},
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds1c46"),
"std_name" : "Mia",
"gender" : "Female",
"fees" : 6000,
"exam_fees" : 500,
"class" : "XI",
"age" : 17,
" Total_marks" : 450
"Result" : "Pass"
},
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds315hj"),
"std_name" : "Mike,
"gender" : "Male",
"fees" : {
"school_fees" :4000,
"exam_fees" : 500,
"pending_fees" : 950,
}
"class" : "V",
"age" : 15,
"Total_marks" : 450
"Result" : "Pass"
}
}
示例 1:使用 $abs 运算符
在此示例中,我们将仅查找女学生的总费用(费用 + 考试费用)。
db.student.aggregate(
[
{$match: {gender : "Female"}},
{
$project:
{
name : 1,
class : 1,
age : 1,
Result : 1,
Total_fees: {$abs: {$add: ["$fees", "$exam_fees"]}}
}
}
]
)
输出结果为:
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d65f"),
"std_name" : "Micky",
"class" : "X",
"age" : 16,
"Result" : "Pass",
"Total_fees" : 5500
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds37832"),
"std_name" : "Jin",
"class" : "X",
"age" : 16,
"Result" : "Pass",
"Total_fees" : 5500
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds1c46"),
"std_name" : "Mia",
"class" : "XI",
"age" : 17,
"Result" : "Pass",
"Total_fees" : 6500,
}
示例 2:MongoDB $abs 运算符(检索嵌入文档中的数据)
在此示例中,我们将查找姓名为 Mike 的学生的总费用(school_fees + Exam_fees + pending_fees)。
db.student.aggregate(
[
{$match : {name : "Mike"}},
{
$project :
{
name : 1,
class : 1,
age : 1,
Result : 1,
Total_fees : {$abs : {$add : ["$fees.school_fees",
"$fees.exam_fees",
"$fees.pending_fees" ]
}
}
}
}
]
)
输出结果为:
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds315hj"),
"std_name" : "Mike,
"class" : "V",
"age" : 15,
"Result" : "Pass",
"Total_fees" : 5450
}
热门文章
优秀文章