當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。