$log (aggregation)

Definition

  • $log

New in version 3.2.

Calculates the log of a number in the specified base and returns theresult as a double.

$log has the following syntax:

  1. { $log: [ <number>, <base> ] }

The <number> expression can be any valid expression as long as it resolves to a non-negative number.

The <base> expression can be any valid expression as long as it resolves to a positivenumber greater than 1.

For more information on expressions, see Expressions.

Behavior

If either argument resolves to a value of null or refers to a field that ismissing, $log returns null. If either argument resolves toNaN, $log returns NaN.

ExampleResults
{ $log: [ 100, 10 ] }2
{ $log: [ 100, Math.E ] } where Math.E is a JavaScriptrepresentation for e.4.605170185988092

Example

A collection examples contains the following documents:

  1. { _id: 1, positiveInt: 5 }
  2. { _id: 2, positiveInt: 2 }
  3. { _id: 3, positiveInt: 23 }
  4. { _id: 4, positiveInt: 10 }

The following example uses log2 in its calculation todetermine the number of bits required to represent the value ofpositiveInt.

  1. db.examples.aggregate([
  2. { $project: { bitsNeeded:
  3. {
  4. $floor: { $add: [ 1, { $log: [ "$positiveInt", 2 ] } ] } } }
  5. }
  6. ])

The operation returns the following results:

  1. { "_id" : 1, "bitsNeeded" : 3 }
  2. { "_id" : 2, "bitsNeeded" : 2 }
  3. { "_id" : 3, "bitsNeeded" : 5 }
  4. { "_id" : 4, "bitsNeeded" : 4 }

See also

$log10 and $ln