MongoDB $log Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Math

What You’ll Learn

The $log operator calculates the logarithm of a number in a specified base. Unlike $ln (which always uses base e), $log lets you choose base 10, base 2, or any other valid base.

01

Custom Base

Pick any valid base.

02

Syntax

[ number, base ].

03

Base 10 & 2

Common log scales.

04

vs $ln

Natural vs custom.

05

Use Cases

Scaling, normalization.

06

Domain Rules

Positive number & base.

Definition and Usage

In MongoDB’s aggregation framework, the $log operator computes logbase(number) — the power you must raise the base to in order to get the number. For example, log₁₀(100) = 2 because 10² = 100, and log₂(8) = 3 because 2³ = 8.

Use $log when your formula requires a specific logarithm base. For natural logarithms (base e), use $ln instead. For base 10 only, you can also use the dedicated $log10 operator.

💡
Beginner Tip

$log takes two arguments in an array: the number first, then the base. Both can be field references or literals. The base must be positive and cannot be 1.

📝 Syntax

The $log operator takes a two-element array: number and base.

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

Common Patterns

mongosh
// Log base 10 of a field
{ $log: [ "$quantity", 10 ] }

// Log base 2 of a literal
{ $log: [ 8, 2 ] }

// Both arguments from fields
{ $log: [ "$value", "$logBase" ] }

Syntax Rules

  • Array form$log requires [ number, base ], not an object.
  • <number> — must be a positive number (or nullnull).
  • <base> — must be positive and cannot equal 1.
  • logb(1) = 0 — for any valid base, the log of 1 is zero.
  • Use inside stages like $project, $addFields, or $set.
  • For base e, prefer $ln; for base 10, consider $log10.

💡 $log vs $ln vs $log10

{ $log: [ 100, 10 ] }2 (base 10)
{ $log: [ 8, 2 ] }3 (base 2)
{ $ln: 10 }≈ 2.302585 (base e)
{ $log10: 100 }2 (same as base-10 $log)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (math)
Syntax{ $log: [ <number>, <base> ] }
ArgumentsNumber (positive), then base (positive, ≠ 1)
OutputLogarithm of number in the given base (or null)
Common stages$project, $addFields, $set
Base 10
{
  $log: [
    "$qty", 10
  ]
}

log₁₀(qty)

Base 2
{
  $log: [ 8, 2 ]
}

Returns 3

log(1)
{
  $log: [ 1, 10 ]
}

Returns 0

Null
{
  $log: [ null, 10 ]
}

Returns null

Examples Gallery

Walk through an orders collection and compute logarithms with different bases using $project.

📚 Order Quantities

Start with an orders collection and compute base-10 logarithms of order quantities.

Sample Input Documents

Suppose you have an orders collection with a quantity field:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "item": "Widget A", "quantity": 10 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "item": "Widget B", "quantity": 100 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "item": "Widget C", "quantity": 1000 }
]

Example 1 — Log Base 10 of a Field

Compute log₁₀(quantity) for each order:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      quantity: 1,
      logQuantity: {
        $log: [ "$quantity", 10 ]
      }
    }
  }
])

How It Works

  • Widget A: log₁₀(10) = 1 because 10¹ = 10.
  • Widget B: log₁₀(100) = 2 because 10² = 100.
  • Widget C: log₁₀(1000) = 3 because 10³ = 1000.

📈 Different Bases and Comparisons

Explore base-2 logarithms and compare $log with $ln.

Example 2 — Log Base 2

Compute log₂(quantity) — useful for binary scales and bit-related calculations:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      quantity: 1,
      log2Quantity: {
        $log: [ "$quantity", 2 ]
      }
    }
  }
])

How It Works

Base-2 logarithm answers: “How many times must I double to reach this quantity?” Powers of 2 give clean integer results — for example, log₂(8) = 3.

Example 3 — Compare $log and $ln Side by Side

See how base-10 log differs from natural log on the same values:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      quantity: 1,
      logBase10: {
        $log: [ "$quantity", 10 ]
      },
      naturalLog: {
        $ln: "$quantity"
      }
    }
  }
])

How It Works

Same input, different bases, different results. Use $log when your formula specifies a base; use $ln when you need base e.

Example 4 — Guard Against Invalid Input

Apply $log only when quantity is positive:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      quantity: 1,
      safeLog: {
        $cond: [
          { $gt: [ "$quantity", 0 ] },
          { $log: [ "$quantity", 10 ] },
          null
        ]
      }
    }
  }
])

How It Works

Logarithm is only defined for positive numbers. If your data might include zero or negatives, check with $gt before calling $log.

Bonus — Base from a Document Field

Both the number and base can come from fields — useful when each record defines its own scale:

mongosh
db.scales.aggregate([
  {
    $project: {
      label: 1,
      result: {
        $log: [ "$value", "$base" ]
      }
    }
  }
])

// Example document:
// { value: 64, base: 4 } → result: 3  (4³ = 64)

How It Works

The second array element is the base. It must be positive and not equal to 1 for every document where you apply $log.

🚀 Use Cases

  • Scaling data — compress values that span many orders of magnitude onto a readable log scale.
  • Normalization — transform skewed distributions before analysis or machine learning.
  • Performance metrics — convert exponential growth curves into linear trends for comparison.
  • Custom bases — compute log base 2, base 4, or any domain-specific base in one expression.

🧠 How $log Works

1

MongoDB reads two arguments

The array [ number, base ] is evaluated from fields, literals, or nested expressions.

Input
2

Validates the domain

Number must be positive; base must be positive and not 1. null input returns null.

Check
3

Computes the logarithm

MongoDB returns logbase(number) — the exponent that raises the base to the number.

Compute
=

Log-scaled value

Your pipeline gets the logarithm in the base you chose, ready for further analysis.

Conclusion

The $log operator gives you flexible logarithm calculations with any valid base inside MongoDB aggregation pipelines. Remember the array syntax { $log: [ number, base ] } and the domain rules for positive inputs.

For natural logs use $ln; for base 10 specifically, $log10 is a convenient shortcut. Choose the operator that matches your formula and keep invalid inputs guarded with $cond when data quality varies.

💡 Best Practices

✅ Do

  • Use array syntax: { $log: [ number, base ] }
  • Ensure the number is positive and the base is positive and ≠ 1
  • Use $log10 when you only need base-10 logarithms
  • Guard with $cond when data may include zero or negatives
  • Compare results with $ln to verify you chose the right base

❌ Don’t

  • Use object syntax like { $log: { expr: base } } — it is invalid
  • Omit the base argument — use $ln for natural log instead
  • Pass base 1 — logarithm base 1 is undefined
  • Confuse base-10 output with natural log results
  • Use $log as a pipeline stage — it is an expression operator

Key Takeaways

Knowledge Unlocked

Five things to remember about $log

Use these points when computing logarithms in MongoDB.

5
Core concepts
🔢 02

Array Syntax

Not an object.

Syntax
🛠 03

log(100)=2

Base 10 example.

Math
🔄 04

vs $ln

Different bases.

Compare
📑 05

Positive Only

Guard invalid input.

Domain

❓ Frequently Asked Questions

$log returns the logarithm of a number in a specified base. It takes two arguments: the number and the base. For example, log base 10 of 100 is 2.
The syntax is { $log: [ <number>, <base> ] }. Both arguments can be field references, literals, or other numeric expressions. The base must be a positive number not equal to 1.
$log lets you choose any valid base. $ln is natural logarithm (base e). $log10 is a shortcut for base-10 logarithm — equivalent to { $log: [ number, 10 ] }.
The number must be positive. The base must be positive and cannot be 1. If either argument is null, $log returns null.
Use $log inside expression stages such as $project, $addFields, $set, and within other numeric expressions when scaling, normalizing, or analyzing data on a log scale.

Continue the Operator Series

Move on to $log10 for base-10 shortcuts, or review $ln for natural logarithms.

Next: $log10 →

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.

5 people found this page helpful