MongoDB $abs实例讲解

时间:2022-04-07
本文章向大家介绍MongoDB $abs实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

MongoDB 提供了不同类型的中使用的算术表达式运算符聚合管道阶段 $abs操作符就是其中之一。这操作员用于查找绝对 指定的数。

用法

{ $abs:<number> }

在这里,数字是一个有效的表达式,直到它解析为一个数字。

  • 如果输入的值为空,则此运算符将返回空。
  • 如果输入的值为 NaN,则此运算符将返回 NaN。
  • 如果输入的值是缺失字段,则此运算符将返回 null。

例子:

在以下示例中,我们正在使用:



Database: GeeksforGeeks

Collection:Employee

Document: three documents that contain the details of the employees in the form of field-value pairs.

使用 $abs 运算符:

在这个例子中,我们将找到开发部门每个员工的总工资。

db.Employee.aggregate([{$match:{department:"Development"}},
... {$project:{name:1, tSalary:{$abs:
                {$add:["$firstSalary", "$secondSalary"]}}}}])

在嵌入式文档中使用 $abs 运算符:

在这个例子中,我们将找到人力资源部门员工的三个月工资。

db.Employee.aggregate([{$match:{department:"HR"}},
... {$project:{name:1, tSalary:{$abs:
                {$add:["$salary.firstMonth",
                        "$salary.secondMonth", 
                        "$salary.thirdMonth"]}}}}])