$pow (aggregation)

On this page本页内容

Definition定义

$pow

New in version 3.2.版本3.2中的新功能。

Raises a number to the specified exponent and returns the result. 将数字幂乘到指定的指数并返回结果。$pow has the following syntax:语法如下所示:

{ $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:在这些情况下:

If either argument resolves to a value of null or refers to a field that is missing, $pow returns null. 如果任一参数解析为null值或引用缺少的字段,$pow返回nullIf either argument resolves to NaN, $pow returns NaN.如果任一参数解析为NaN$pow返回NaN

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