MongoDB 提供了不同類型的中使用的算術表達式運算符聚合管道階段$pow操作符就是其中之一。這操作員用於查找指定 index 的數字並返回結果。
用法:
{ $pow:[ <number>, <exponent> ] }
在這裏,數字和 index 是有效的表達式,直到它解析為數字。
- 如果輸入的值解析為 null,則此運算符將返回 null。
- 如果輸入的值解析為 NaN,則此運算符將返回 NaN。
- 如果輸入的值引用了缺失的字段,則此運算符將返回 null。
結果將與輸入的類型相同,但可以在輸入時更改不能像在那種類型中準確表示下列的案例:
- 這個如果結果表示為 64 位整數,則 32 位整數將轉換為 64 位整數。
- 這個如果結果未表示為 64 位整數,則 32 位整數將轉換為雙精度數。
- 如果結果未表示為 64 位整數,則 64 位整數將轉換為 double。
例子:
在以下示例中,我們正在使用:
Database: GeeksforGeeks
Collection:example
Document: two documents that contain the details of the shapes in the form of field-value pairs.
使用 $pow 運算符:
在這個例子中,我們將使用 $pow 運算符找到正方形的麵積(即 (side)2 )。這裏,$pow 操作符包含兩個參數,第一個是邊域的值(即 2),第二個是 index (即 2)。
db.example.aggregate([ ... {$match:{name:"Square"}}, ... {$project:{area:{$pow:["$side", 2]}}}])
在嵌入式文檔中使用 $pow 運算符:
在這個例子中,我們將找到 (measurement.height +measurement.width)2 的值 使用 $pow 運算符。這裏,$pow 運算符包含兩個參數,第一個是measurement.height 和measurement.width 字段值的總和,第二個是 index (即2)。
db.example.aggregate([ {$match:{name:"Rectangle"}}, ... {$project:{result: ... {$pow:[{$add:["$measurement.height", "$measurement.width"]}, 2]}}}])
相關用法
- MongoDB $mul用法及代碼示例
- MongoDB $rename用法及代碼示例
- MongoDB $setOnInsert用法及代碼示例
- MongoDB $ln用法及代碼示例
- MongoDB $floor用法及代碼示例
- MongoDB $divide用法及代碼示例
- MongoDB $add用法及代碼示例
- MongoDB $ceil用法及代碼示例
- MongoDB $sqrt用法及代碼示例
- MongoDB $multiply用法及代碼示例
- MongoDB $mod用法及代碼示例
- MongoDB $log10用法及代碼示例
- MongoDB $log用法及代碼示例
- MongoDB $abs用法及代碼示例
- MongoDB $strcasecmp用法及代碼示例
注:本文由純淨天空篩選整理自ankita_saini大神的英文原創作品 MongoDB $pow Operator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。