当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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"]}}}}])

相关用法


注:本文由纯净天空筛选整理自ankita_saini大神的英文原创作品 MongoDB $abs operator。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。