$pow (aggregation)
On this page本页内容
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行为
The result will have the same type as the input except when it cannot be represented accurately in that type. In these cases:结果将具有与输入相同的类型,除非无法在该类型中准确表示。在这些情况下:
A 32-bit integer will be converted to a 64-bit integer if the result is representable as a 64-bit integer.如果结果可以表示为64位整数,则32位整数将被转换为64位的整数。A 32-bit integer will be converted to a double if the result is not representable as a 64-bit integer.如果结果不能表示为64位整数,则32位整数将转换为双精度。A 64-bit integer will be converted to double if the result is not representable as a 64-bit integer.如果结果不能表示为64位整数,则64位整数将被转换为双。
If either argument resolves to a value of 如果其中一个参数解析为null
or refers to a field that is missing, $pow
returns null
. null
值或引用了缺失的字段,$pow
将返回null
。If either argument resolves to 如果任一参数解析为NaN
, $pow
returns NaN
.NaN
,$pow
将返回NaN
。
{ $pow: [ 5, 0 ] } | 1 |
{ $pow: [ 5, 2 ] } | 25 |
{ $pow: [ 5, -2 ] } | 0.04 |
{ $pow: [ -5, 0.5 ] } | NaN |
Example实例
A collection named 一个名为quizzes
contains the following documents:quizzes
的集合包含以下文档:
{
"_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 }