参考 > 参考 > 经营者 > 聚合管道运营商 > $ log(聚合)
在本页面
$log
3.2版中的新功能。
以指定的底数计算数字的对数,并以双精度值返回结果。
$log 具有以下语法:
{ $log: [ <number>, <base> ] }
该<number>表达式可以是任何有效表达式,只要它可以解析为非负数。
<number>
该<base>表达式可以是任何有效表达式,只要它解析为大于的正数即可1。
<base>
1
有关表达式的更多信息,请参见表达式。
如果任何一个参数解析为null或指向缺少的字段,则$log返回null。如果任一参数解析为 NaN,则$log返回NaN。
null
NaN
{ $log: [ 100, 10 ] }
2
{ $log: [ 100, Math.E ] }
Math.E
4.605170185988092
集合examples包含以下文档:
examples
{ _id: 1, positiveInt: 5 } { _id: 2, positiveInt: 2 } { _id: 3, positiveInt: 23 } { _id: 4, positiveInt: 10 }
以下示例在计算中使用log 2来确定表示的值所需的位数 positiveInt。
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 }
也可以看看
$log10 和 $ln
$log10
$ln