MongoDB $sqrt 运算符

2024 年 9 月 6 日 | 3 分钟阅读

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

MongoDB 提供了各种算术表达式运算符。 $sqrt 运算符是这些算术表达式运算符之一。 $sqrt 运算符用于计算正数的平方根,并将其输出为双精度浮点数。此运算符也用于聚合管道阶段。

$sqrt 运算符的语法

< number > 可以是任何有效数字,只要它解析为非负数即可。

重要提示

  1. 如果数字引用缺失字段或 null,则 $sqrt 运算符返回 null。
  2. 如果数字是 NaN,则 $sqrt 运算符返回 NaN。
序号示例输出
1.{ $sqrt: 4 }2
2.{ $sqrt: 15 }3.872983346207417
3.{ $sqrt: -2 }Error
4.{ $sqrt: null}Null

示例

假设我们有一个包含以下文档的 items 集合。

>db.items.find().pretty()
{
        {
         "_id" : 1, 
         "item_name" : "bat",
         "quantity" : 4
        }
        {
         "_id" : 2, 
         "item_name" : "ball",
         "quantity" : null
        }
        {
         "_id" : 3, 
         "item_name" : "box",
         "details" : { 
                           "length" : 20,
                           "width" : 25
                          }
        }
        {
         "_id" : 4, 
         "item_name" : "ball",
         "quantity" : null
        }
        {
         "_id" : 5, 
         "item_name" : "bat",
         "quantity" : 20
        }
        {
         "_id" : 6, 
         "item_name" : "toy",
         "quantity" : -10
        }
        {
         "_id" : 7, 
         "item_name" : "bat",
         "quantity" : 75
        }
        {
         "_id" : 8, 
         "item_name" : "bat",
         "quantity" : 45
        }
}

示例 1:使用 $sqrt 运算符查找任何字段的平方根

在此示例中,我们使用 $sqrt 运算符查找“数量”字段的平方根。

输出

{
         "_id" : 1, 
         "item_name" : "bat",
         "quantity" : 4,
         "result" : 2
}
{
         "_id" : 5, 
         "item_name" : "bat",
         "quantity" : 20,
         "result" : 4.472135954999579
}
{
         "_id" : 7, 
         "item_name" : "bat",
         "quantity" : 75,
         "result" : 8.660254037844386
}
{
         "_id" : 8, 
         "item_name" : "bat",
         "quantity" : 45,
         "result" : 6.708203932499369
}

示例 2:字段的负值

$sqrt 运算符仅支持必须大于或等于 0 的正数。如果参数值为负数,则会报错。让我们对玩具文档应用 $sqrt 运算符。

输出

uncaught exception: Error: command failed: {
	"ok": 0,
	"errmsg": "$sqrt's argument must be greater than or equal to 0",
	"code": 28714,
	"codeName": "Location28714"
} : 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

示例 3:字段的 null 值

如果字段值为 null,则 $sqrt 运算符返回 null。 让我们对 ball 文档应用 $sqrt 运算符。

输出

{
         "_id" : 2, 
         "item_name" : "ball",
         "quantity" : null,
         "result" : null
}
{
         "_id" : 4, 
         "item_name" : "ball",
         "quantity" : null,
         "result" : null
}

示例 4:不存在的字段

如果参数引用缺失字段,则 $sqrt 运算符返回 null。 在此示例中,我们使用 $sqrt 运算符查找“价格”字段的平方根。

输出

{
         "_id" : 5, 
         "item_name" : "bat",
         "quantity" : 20,
         "result" : null
}