MongoDB $pow 运算符

17 Mar 2025 | 4 分钟阅读

MongoDB 中的 $pow 运算符是什么?

MongoDB 提供了各种算术表达式运算符。 $pow 运算符是这些运算符之一。 此运算符用于聚合管道阶段。 此运算符用于查找数字的指数(幂)。

一个数的指数是什么?

指数(幂)是将一个数乘以它本身的结果。 通常,指数在书写中表示为这样的图表。

MongoDB $pow Operator

$pow 运算符的语法

< number > 和 < exponent > 可以是任何有效的表达式,直到它解析为数字。

重要提示

  1. 如果数字为 null,则 $pow 运算符返回 null。
  2. 如果数字引用一个缺失的字段,则 $pow 运算符返回 null。
  3. 如果数字是 NaN,则 $pow 运算符返回 NaN。
序号示例输出
1.{ $pow: [ 4, 0 ] }1
2.{ $pow: [ 4, 2 ] }16
3.{ $pow: [ 4, -2 ] }0.0625
4.{ $pow: [ -4, 0.5 ] }NaN

示例

在下面的示例中,我们将使用

>db.shapes.find().pretty()
{
        {
         "_id" : 1, 
         "name" : "rectangle",
         "area" : 16
        }
        {
         "_id" : 2, 
         "name" : "square",
         "area" : 10
        }
        {
         "_id" : 3, 
         "name" : "circle",
         "perimeter" : 15,
         "area" : 10,
         "details" : { 
                           "radius" : 3,
                           "diameter" : 6
                          }
        }
        {
         "_id" : 4, 
         "name" : "rectangle",
         "area" : 0
        }
        {
         "_id" : 5, 
         "name" : "oval",
         "area" : 20
        }
        {
         "_id" : 6, 
         "name" : "triangle",
         "area" : 5
        }
        {
         "_id" : 7, 
         "name" : "rectangle",
         "area" : null
        }
}

示例 1:使用 $pow 运算符

在此示例中,我们使用 $pow 运算符将矩形形状中的“area”字段按指定的指数取幂。

输出

{
         "_id" : 1, 
         "name" : "rectangle",
         "area" : 16,
         "result" : 4096
}
{
         "_id" : 4, 
         "name" : "rectangle",
         "area" : 0,
         "result" : 0
}
{
         "_id" : 7, 
         "name" : "rectangle",
         "area" : null,
         "result" : null
}

在此示例中,我们使用 area 字段作为底数,3 作为指数。 因此,矩形的每个“area”字段都已取 3 次方。

示例 2:负指数

如果底数为零 (0) 且指数为负数,则无法对该数字进行求幂。 在这种情况下,它将返回错误消息。

输出

uncaught exception : Error : command failed : {
	"ok" : 0,
	"errmsg" : "$pow cannot take a base of 0.and a negative exponent",
	"code" : 28764,
	"codeName" : "Location28764"4' [ ln;' lj; h
Lh;klh[pjlkh[pkoh[khp[o
} : aggregate failed:
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:618:17
assert.commandWorked@src/mongo/shell/assert.js:708:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1046 : 12
@(shell) : 1 : 1

错误清楚地说明:“$pow 不能取 0 为底数,负数为指数”。

输出

{
         "_id" : 5, 
         "name" : "oval",
         "area" : 20,
         "result" : 0.000125  
}

示例 3:空指数

我们已经在“示例 1”中看到,如果底数为 null,结果也会变为 null。

如果指数的值为 null,它仍然会返回 null。

输出

{
         "_id" : 6, 
         "name" : "triangle",
         "area" : 5,
         "result" : null  
}

示例 4:不存在的字段

如果将 $pow 运算符应用于程序中不存在的字段,则返回 null。

输出

{
         "_id" : 2, 
         "name" : "square",
         "area" : 10,
         "result" : null  
}