MongoDB $log Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $log?

$log is a MongoDB aggregation expression that returns the logarithm of a number in a base you choose. Example: log10(100) = 2 because 10² = 100.

Remember
$log = logarithm with a custom base

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

number → non-negative
base   → greater than 1
result → double (usually)

{ $log: [ 100, 10 ] }  →  2
{ $log: [ 8, 2 ] }     →  3

null / missing → null
NaN → NaN
NeedPrefer
Any base (2, 10, …)$log
Base 10 only$log10
Natural log (base e)$ln

How to Use $log in MongoDB

Pass the number and the base as a two-element array, then store the result in a stage.

  1. Choose an expression stage ($addFields or $project).
  2. Write { $log: [ "$value", 10 ] } (number first, base second).
  3. Confirm the number is non-negative and the base is greater than 1.
  4. Use the result for scaling, bits math, or further expressions.
PieceRequired?Role
NumberYesValue to take the log of (≥ 0)
BaseYesLog base (> 1)
Result—Double (or decimal if an operand is decimal)

Pseudocode

Pseudocode
for each document:
    n = evaluate(numberExpression)
    b = evaluate(baseExpression)
    if n or b is null / missing:
        result = null
    else if n or b is NaN:
        result = NaN
    else:
        result = log_b(n)   // logarithm of n in base b
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while computing logarithms.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $log: [ "$value", 10 ] }
NumberNon-negative
BaseGreater than 1
Related$log10, $ln, $pow
Sample checklog10(100) = 2

Live Preview

Watch $log compute logbase(number) for a few pairs.

Simulates { $log: [ number, base ] } (same idea as the mongosh examples below).

Result
number = 100
base   = 10

$log → 2

Check: 10^2 = 100 ✓

{ result: 2 }

Worked Walkthrough — log10(100)

A reading stores value: 100. We want the base-10 logarithm.

Calculation
Document:
  { value: 100 }

$log: [ "$value", 10 ]

Ask: 10 to what power equals 100?
  10^2 = 100

Result:
  2

Check: pow(10, 2) = 100 ✓

MongoDB Examples

We use one number document. First we store it, then we compute log10, then we use log2 to estimate bits needed. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one reading with value 100 and an integer 8 we will use for a log2 bits example.

mongosh
db.numbers.insertOne({
  _id: 1,
  label: "Scale",
  value: 100,
  int: 8
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in numbers. Run find() to see it:

mongosh
db.numbers.find()

Read that document like this:

Field in MongoDBValuePlain English
value100Number for base-10 log
int8Number for base-2 bits math
Picture
100  --$log base 10-->  2     (because 10^2 = 100)
  8  --$log base 2 -->  3     (because 2^3 = 8)

How It Works

  1. Insert once. insertOne adds a single document to numbers.
  2. Store positive numbers. Both value and int are valid $log inputs.
  3. find() shows the same shape. Ready for the log examples next.

Example 2 — Log Base 10

Goal: add a log10 field with log10(value).

mongosh
db.numbers.aggregate([
  {
    $addFields: {
      log10: { $log: [ "$value", 10 ] }
    }
  }
]);

How It Works

  1. Read the number. "$value" is 100.
  2. Set the base. Second argument 10 means base-10 log.
  3. Get the exponent. 10² = 100, so the result is 2.
  4. Keep all fields. $addFields adds log10 next to value.

Example 3 — Bits with Log Base 2

Estimate how many bits are needed to represent int: floor(1 + log2(int)).

mongosh
db.numbers.aggregate([
  {
    $project: {
      int: 1,
      bitsNeeded: {
        $floor: {
          $add: [
            1,
            { $log: [ "$int", 2 ] }
          ]
        }
      }
    }
  }
]);

How It Works

  1. Take log base 2. { $log: [ "$int", 2 ] } → log2(8) = 3.
  2. Add one. $add makes 1 + 3 = 4.
  3. Floor the result. $floor keeps the integer bit count (here already whole).
  4. Check: binary of 8 is 1000 → 4 bits.

Edge Cases & Pitfalls

Check these before using $log in production pipelines.

domain

Base must be greater than 1

Bases like 1, 0, or negatives are invalid. Use a base such as 2 or 10.

domain

Number must be non-negative

Negative inputs are outside the domain. Prefer positive numbers for normal finite logs.

args

Order is [number, base]

{ $log: [ 10, 100 ] } is not the same as { $log: [ 100, 10 ] }. Number first, base second.

null

Null or missing → null

If either argument is null or missing, $log returns null, not an error.

shortcut

Prefer $log10 / $ln when fixed

For base 10 use $log10. For natural log use $ln. Keep $log when the base varies.

Performance Notes

ApproachCostBest for
$log aloneCheap per documentScaling and log transforms
$log + $floorStill lightweightBits / bucket estimates
Precompute on writeWrite cost, cheaper readsVery frequent log queries

Logarithms are inexpensive compared with large sorts or joins. Filter early with $match when only some documents need the log field.

Key Takeaways

  • Role: number + base → logarithm (double).
  • Syntax: { $log: [ number, base ] }.
  • Domain: number ≥ 0, base > 1.
  • Shortcuts: $log10 and $ln for fixed bases.

One line: $log answers “base to what power equals this number?”—with a base you choose.

Frequently Asked Questions

$log returns the logarithm of a number in a base you choose. For example, { $log: [ 100, 10 ] } returns 2 because 10² = 100. Use it inside aggregation stages such as $project and $addFields.
The syntax is { $log: [ <number>, <base> ] }. Both arguments can be literals, field paths, or other numeric expressions. The result is typically a double.
The number must resolve to a non-negative value. The base must resolve to a positive number greater than 1. Null or missing arguments return null; NaN returns NaN.
$log lets you pick any valid base. $ln is natural log (base e). $log10 is a shortcut for base 10 — the same idea as { $log: [ number, 10 ] }.
Close, but JavaScript Math.log is natural log only. For a custom base in JS you use Math.log(n) / Math.log(base). MongoDB $log takes the base as the second argument.
Use $log inside expression stages such as $project, $addFields, and $set when scaling data, computing bits needed (log base 2), or normalizing values on a log scale.

Next: $log10

Compute the base-10 logarithm with a dedicated operator.

$log10 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful