Definition定义
$powRaises a number to the specified exponent and returns the result.将一个数字幂乘到指定的指数并返回结果。$powhas the following syntax:$pow的语法如下:{ $pow: [ <number>, <exponent> ] }The<number>expression can be any valid expression as long as it resolves to a number.<number>表达式可以是任何有效的表达式,只要它解析为数字。The<exponent>expression can be any valid expression as long as it resolves to a number.<exponent>表达式可以是任何有效的表达式,只要它解析为数字。You cannot raise您不能将0to a negative exponent.0幂乘到负指数。
Behavior行为
When input types are mixed, 当输入类型混合时,$pow promotes the smaller input type to the larger of the two. A type is considered larger when it represents a wider range of values. The order of numeric types from smallest to largest is: $pow会将较小的输入类型升级为两者中较大的输入类型。当一个类型代表更宽的值范围时,它被认为更大。数字类型从最小到最大的顺序是:integer → long → double → decimal
The larger of the input types also determines the result type unless the operation overflows and is beyond the range represented by that larger data type. In cases of overflow, 较大的输入类型也决定了结果类型,除非操作溢出并且超出了较大数据类型表示的范围。在溢出的情况下,$pow promotes the result according to the following order:$pow会按照以下顺序提升结果:
If the larger input type is如果较大的输入类型为integer, the result type is promoted tolong.integer,则结果类型将提升为long。If the larger input type is如果较大的输入类型为long, the result type is promoted todouble.long,则结果类型将提升为double。If the larger type is如果较大的类型是doubleordecimal, the overflow result is represented as + or - infinity. There is no type promotion of the result.double或decimal,则溢出结果表示为+或-无穷大。结果没有类型推广。
If either argument resolves to a value of 如果任一参数解析为null or refers to a field that is missing, $pow returns null. If either argument resolves to NaN, $pow returns NaN.null值或引用缺少的字段,$pow将返回null。如果任一参数解析为NaN,$pow将返回NaN。
{ $pow: [ 5, 0 ] } | 1 |
{ $pow: [ 5, 2 ] } | 25 |
{ $pow: [ 5, -2 ] } | 0.04 |
{ $pow: [ -5, 0.5 ] } | NaN |
Example示例
Create a collection called 使用以下文档创建一个名为quizzes with the following documents:quizzes的集合:
db.quizzes.insertMany( [
{
_id : 1,
scores : [
{ name : "dave123", score : 85 },
{ name : "dave2", score : 90 },
{ name : "ahn", score : 71 }
]
},
{
_id : 2,
scores : [
{ name : "li", quiz : 2, score : 96 },
{ name : "annT", score : 77 },
{ name : "ty", score : 82 }
]
}
] )
The following example calculates the variance for each quiz:以下示例计算每个测验的方差:
db.quizzes.aggregate( [
{ $project: { variance: { $pow: [ { $stdDevPop: "$scores.score" }, 2 ] } } }
] )
The operation returns the following results:该操作返回以下结果:
{ _id : 1, variance : 64.66666666666667 }
{ _id : 2, variance : 64.66666666666667 }