$pow (aggregation)

On this page本页内容

Definition定义

$pow

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

  • 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返回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 }
←  $or (aggregation)$push (aggregation) →