Docs 菜单

$pow (aggregation)

在此页面上

$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.

The <exponent> expression can be any valid 表达式(expression) as long as it resolves to a number.

You cannot raise 0 to a negative exponent.

The result will have the same type as the input except when it cannot be represented accurately in that type. In these cases:

  • 如果结果可表示为 64 位整数,则 32 位整数将被转换为 64 位整数。

  • 如果结果不能表示为 64 位整数,则 32 位整数将被转换为 double。

  • 如果结果不能表示为 64 位整数,则 64 位整数将被转换为 double。

如果任一参数解析为 null 的值或引用了缺失的字段,$pow 会返回 null。如果任一参数解析为 NaN$pow 会返回 NaN

例子
结果

{ $pow: [ 5, 0 ] }

1

{ $pow: [ 5, 2 ] }

25

{ $pow: [ 5, -2 ] }

0.04

{ $pow: [ -5, 0.5 ] }

NaN

使用以下文档创建名为 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 ] } } }
] )

操作返回以下结果:

{ _id : 1, variance : 64.66666666666667 }
{ _id : 2, variance : 64.66666666666667 }

在此页面上