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


MongoDB $add用法及代碼示例

MongoDB 提供了不同類型的中使用的算術表達式運算符聚合管道階段$add操作符就是其中之一。這操作員用於添加數字或日期。如果 $add操作員 添加日期,然後它會對待其他參數作為毫秒並添加到指定的日期。

用法:

{ $add: [ <Expression1>, <Expression2>, ... <ExpressionN>] }

在這裏,表達式必須是一個有效的表達式,如數字或日期。

例子:

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



Database: GeeksforGeeks

Collection:Employee

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

使用 $add 運算符添加數字:

在這個例子中,我們將找到開發部門每個員工的總工資。

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

使用 $add 運算符在嵌入文檔中添加數字:

在這個例子中,我們將找到人力資源部門員工的三個月工資。

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

使用 $add 運算符添加日期:

在此示例中,我們將通過在測試部門的 projectEndDate 字段中添加 5 天(即 5*24*60*60000)來延長項目的最後日期。

db.Employee.aggregate([{$match:{department:"Testing"}},
... {$project:{extendprojectDate:
          {$add:["$projectEndDate", 5*24*60*60000]}}}])

相關用法


注:本文由純淨天空篩選整理自ankita_saini大神的英文原創作品 MongoDB $add Operator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。