Database Manual / Reference / Query Language / Expressions

$pow (aggregation)(聚合)

Definition定义

$pow

Raises a number to the specified exponent and returns the result. $pow has 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 0 to 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 to long.如果较大的输入类型为integer,则结果类型将提升为long
  • If the larger input type is long, the result type is promoted to double.如果较大的输入类型为long,则结果类型将提升为double
  • If the larger type is double or decimal, the overflow result is represented as + or - infinity. There is no type promotion of the result.如果较大的类型是doubledecimal,则溢出结果表示为+或-无穷大。结果没有类型推广。

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

Example示例Results结果
{ $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 }