MongoDB $log10 运算符

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

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

MongoDB 提供了各种算术表达式运算符。$log10 运算符是其中之一。$log10 运算符用于计算一个数的以 10 为底的对数,并以双精度数的形式返回结果。$log10 运算符是在 MongoDB 3.2 版本中添加的。

$log10 运算符等效于以下表达式 ( $log : [ < number >, 10 ] )。

$log10 运算符的语法

其中,< number > 可以是任何解析为非负数(即 0、1、2、3... n)的有效表达式。

重要提示

  1. 如果 <number> 值为 null,则返回 null。
  2. 如果输入值引用缺失字段,则返回 null。
  3. 如果 <number> 值为 NaN,则返回 NaN。
示例输出
{ $log10 : 1 }0
{ $log10 : 10 }1
{ $log10 : 100 }2
{ $log10 : 1000 }3
{ $log10 : null }null
{ $log10 : 10 * 1 }NaN

示例

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

示例 1:使用 $log10 运算符

在本例中,我们将使用 $log10 运算符计算所有 "toys" 文档中 "Value" 字段的以 10 为底的对数。

输出

{
         "_id" : 1, 
         "name" : "toys",
         "value" : 100,
         "log10Value" : 2
}
{
         "_id" : 3, 
         "name" : "toys",
         "value" : 28,
         "log10Value" : 1.44715803134
}
{
         "_id" : 5, 
         "name" : "toys",
         "value" : 30,
         "log10Value" : 1.47712125472
}
{
         "_id" : 8, 
         "name" : "toys",
         "value" : 20,
         "log10Value" : 1.30102999566
}

示例 2:超出范围的值

log10 运算符只接受正数,如果 <number> 的值为负数,则返回错误。在本例中,我们将使用 $log10 运算符计算 "headphone" 文档中 "Value" 字段的以 10 为底的对数。

输出

uncaught exception : Error : command failed : {
	"ok": 0,
	"errmsg": "$log10's argument must be a positive number, but is -10",
	"code": 28761,
	"codeName": "Location28761"
}: 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 值

使用 $log10 运算符时,Null 值变为零。让我们针对 pen 文档中的 "Value" 字段运行 $log10 运算符。

输出

{
         "name" : "pen",
         "value" : null,
         "log10Value" : null
}
{
         "name" : "pen",
         "value" : 10,
         "log10Value" : 1         
}

示例 4:NaN 值

输出

{
         "name" : "toys",
         "value" : 100,
         "log10Value" : NaN         
}

示例 5:不存在的字段

如果对不存在的字段应用 $log10 运算符,则返回 null。

输出

{
         "name" : "toys",
         "value" : 28,
         "log10Value" : null         
}

下一个主题MongoDB $cmp 运算符