On this page
$log (aggregation)
在本页面
Definition
$log
- 3.2 版中的新功能。
以指定的底数计算数字的对数,并以双精度形式返回结果。
$log具有以下语法:
{ $log: [ <number>, <base> ] }
<number>
表达式可以是任何有效的expression,只要它解析为非负数即可。
<base>
表达式可以是任何有效的expression,只要它解析为大于1
的正数即可。
有关表达式的更多信息,请参见Expressions。
Behavior
如果任一自变量解析为值null
或引用了缺少的字段,则$log
返回null
。如果任一自变量解析为NaN
,则$log
返回NaN
。
Example | Results |
---|---|
{ $log: [ 100, 10 ] } |
2 |
{ $log: [ 100, Math.E ] } ,其中Math.E 是* e *的 JavaScript 表示形式。 |
4.605170185988092 |
Example
集合examples
包含以下文档:
{ _id: 1, positiveInt: 5 }
{ _id: 2, positiveInt: 2 }
{ _id: 3, positiveInt: 23 }
{ _id: 4, positiveInt: 10 }
以下示例在计算中使用 log2 来确定表示positiveInt
值所需的位数。
db.examples.aggregate([
{ $project: { bitsNeeded:
{
$floor: { $add: [ 1, { $log: [ "$positiveInt", 2 ] } ] } } }
}
])
该操作返回以下结果:
{ "_id" : 1, "bitsNeeded" : 3 }
{ "_id" : 2, "bitsNeeded" : 2 }
{ "_id" : 3, "bitsNeeded" : 5 }
{ "_id" : 4, "bitsNeeded" : 4 }