Definition定义
$logCalculates the log of a number in the specified base and returns the result as a double.计算指定基数内数字的对数,并将结果作为双精度数返回。$loghas the following syntax:具有以下语法:{ $log: [ <number>, <base> ] }The<number>expression can be any valid expression as long as it resolves to a non-negative number.<number>表达式可以是任何有效的表达式,只要它解析为非负数。The<base>expression can be any valid expression as long as it resolves to a positive number greater than1.<base>表达式可以是任何有效的表达式,只要它解析为大于1的正数。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
The default return type is a 默认返回类型是double. If at least one operand is a decimal, then the return type is a decimal.double。如果至少有一个操作数是decimal,则返回类型是decimal。
If either argument resolves to a value of 如果任一参数解析为null or refers to a field that is missing, $log returns null. If either argument resolves to NaN, $log returns NaN.null值或引用缺少的字段,$log将返回null。如果任一参数解析为NaN,$log将返回NaN。
{ $log: [ 100, 10 ] } | 2 |
{ $log: [ 100, Math.E ] }Math.E is a JavaScript representation for e.Math.E是e的JavaScript表示。 | 4.605170185988092 |
Example示例
A collection integers contains the following documents:integers集合包含以下文档:
db.integers.insertMany( [
{ _id: 1, int: 5 },
{ _id: 2, int: 2 },
{ _id: 3, int: 23 },
{ _id: 4, int: 10 }
] )
The following example uses log 2 in its calculation to determine the number of bits required to represent the value of 以下示例在计算中使用log 2来确定表示int.int值所需的位数。
db.integers.aggregate([
{ $project: { bitsNeeded:
{
$floor: { $add: [ 1, { $log: [ "$int", 2 ] } ] } } }
}
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "bitsNeeded" : 3 }
{ "_id" : 2, "bitsNeeded" : 2 }
{ "_id" : 3, "bitsNeeded" : 5 }
{ "_id" : 4, "bitsNeeded" : 4 }