MongoDB $ln Operator

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

What You’ll Learn

The $ln operator calculates the natural logarithm of a number in an aggregation expression. It uses base e (Euler’s number, about 2.71828) — the same as Math.log() in JavaScript.

01

Natural Log

Logarithm base e.

02

Syntax

{ $ln: expr }.

03

Positive Input

Values must be > 0.

04

Key Values

ln(1)=0, ln(e)=1.

05

Use Cases

Growth, science, stats.

06

vs $log

Base e vs custom base.

Definition and Usage

In MongoDB’s aggregation framework, the $ln operator computes the natural logarithm of a numeric expression. For example, ln(1) = 0 and ln(e) ≈ 1. This is useful when working with exponential growth, concentration scales, entropy calculations, or any formula that uses base-e logarithms.

Think of $ln as MongoDB’s pipeline version of JavaScript’s Math.log() — not Math.log10(), which uses base 10.

💡
Beginner Tip

Natural logarithm answers the question: “To what power must e be raised to get this number?” For example, because e¹ ≈ 2.718, we know ln(2.718) ≈ 1.

📝 Syntax

The $ln operator takes one numeric expression:

mongosh
{ $ln: <expression> }

Common Patterns

mongosh
// Field reference
{ $ln: "$concentration" }

// Literal number
{ $ln: 10 }

// Nested expression
{ $ln: { $add: [ "$value", 1 ] } }

Syntax Rules

  • $ln — returns the natural logarithm (base e) of the expression.
  • <expression> — must evaluate to a positive number for a valid result.
  • ln(1) = 0 — the logarithm of 1 is always zero, in any base.
  • null input — returns null.
  • Use inside stages like $project, $addFields, or $set.
  • For logarithms with a custom base, use $log instead.

💡 Input Domain for $ln

ln(1)0
ln(e)1 (where e ≈ 2.71828)
ln(10)≈ 2.302585
Zero or negative → not valid for natural log; guard with $cond if needed

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (math)
Syntax{ $ln: <expression> }
Basee (natural logarithm)
Valid inputPositive numbers (and nullnull)
Common stages$project, $addFields, $set
ln(1)
{
  $ln: 1
}

Returns 0

Field
{
  $ln: "$value"
}

Log of field

ln(10)
{
  $ln: 10
}

≈ 2.302585

Null
{
  $ln: null
}

Returns null

Examples Gallery

Walk through a sample measurements collection and apply $ln to transform positive numeric values step by step.

📚 Lab Measurements

Start with a measurements collection and compute natural logarithms with $project.

Sample Input Documents

Suppose you have a measurements collection with positive concentration values:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "sample": "A", "concentration": 1 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "sample": "B", "concentration": 2.718281828 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "sample": "C", "concentration": 10 }
]

Example 1 — Basic $ln on a Field

Add a logConcentration field using $ln:

mongosh
db.measurements.aggregate([
  {
    $project: {
      sample: 1,
      concentration: 1,
      logConcentration: { $ln: "$concentration" }
    }
  }
])

How It Works

  • Sample A: concentration is 1, so ln(1) = 0.
  • Sample B: concentration is approximately e, so ln(e) ≈ 1.
  • Sample C: concentration is 10, so ln(10) ≈ 2.302585.

📈 Practical Patterns

Combine $ln with other operators for growth analysis and safe transformations.

Example 2 — Log Growth Rate from a Ratio

When comparing a current value to a baseline, the natural log of the ratio measures proportional change:

mongosh
db.measurements.aggregate([
  {
    $project: {
      sample: 1,
      current: "$concentration",
      baseline: 2,
      logGrowth: {
        $ln: {
          $divide: [ "$concentration", 2 ]
        }
      }
    }
  }
])

How It Works

ln(current / baseline) expresses relative change on a log scale. Positive values mean growth above the baseline; negative values mean decline. This pattern is common in economics and biology.

Example 3 — $ln with Literal Numbers

Compute natural logarithms for fixed constants in a projection:

mongosh
db.measurements.aggregate([
  {
    $project: {
      sample: 1,
      lnOfOne: { $ln: 1 },
      lnOfTen: { $ln: 10 },
      lnOfE: { $ln: 2.718281828 }
    }
  }
])

How It Works

Literal arguments work the same as field references. These three values are handy reference points when learning how natural logarithms behave.

Example 4 — Guard Against Non-Positive Values

Use $cond to apply $ln only when the input is positive:

mongosh
db.measurements.aggregate([
  {
    $project: {
      sample: 1,
      concentration: 1,
      safeLog: {
        $cond: [
          { $gt: [ "$concentration", 0 ] },
          { $ln: "$concentration" },
          null
        ]
      }
    }
  }
])

How It Works

Natural logarithm is only defined for positive numbers. If your data might include zero or negative values, check with $gt before calling $ln, and return null or a default when the input is invalid.

Bonus — Log Difference Between Two Fields

Compute ln(a) - ln(b), which equals ln(a/b):

mongosh
db.measurements.aggregate([
  {
    $project: {
      sample: 1,
      logRatio: {
        $subtract: [
          { $ln: "$concentration" },
          { $ln: 2 }
        ]
      }
    }
  }
])

How It Works

This is equivalent to Example 2’s ln(concentration / 2) thanks to the logarithm property: ln(a) - ln(b) = ln(a/b). Choose whichever form reads clearer in your pipeline.

🚀 Use Cases

  • Scientific data — transform concentration or intensity values onto a log scale.
  • Growth analysis — compute log returns and proportional change from ratios.
  • Statistics — prepare data for models that assume log-normal distributions.
  • Entropy & information theory — formulas often use natural logarithms.

🧠 How $ln Works

1

MongoDB evaluates the input

The expression inside $ln resolves to a number from a field, literal, or nested operator.

Input
2

Checks for null

If the input is null, $ln returns null without error.

Null
3

Computes natural log

For positive numbers, MongoDB returns logₑ(x) — the power you raise e to in order to get x.

Compute
=

Log-scaled output

Your pipeline gets the natural logarithm, ready for further math or reporting.

Conclusion

The $ln operator brings natural logarithm calculations into MongoDB aggregation pipelines. Use it when your formulas require base-e logs — the same family as JavaScript’s Math.log().

Remember the domain: input must be positive. Guard with $cond when data quality is uncertain, and reach for $log when you need a custom logarithm base.

💡 Best Practices

✅ Do

  • Ensure input values are positive before applying $ln
  • Use $cond to handle zero, negative, or missing values
  • Remember ln(1) = 0 as a quick sanity check
  • Use $log when you need base 10 or another custom base
  • Combine with $divide for log-ratio growth calculations

❌ Don’t

  • Apply $ln to zero or negative numbers without guarding
  • Confuse $ln (base e) with base-10 logarithm
  • Use $ln as a pipeline stage — it is an expression operator
  • Expect meaningful results from non-numeric strings
  • Forget that null input returns null

Key Takeaways

Knowledge Unlocked

Five things to remember about $ln

Use these points when working with natural logarithms in MongoDB.

5
Core concepts
🔢 02

ln(1) = 0

Key reference.

Math
🛠 03

Positive Only

Guard invalid input.

Domain
🔄 04

Log Ratios

ln(a/b) growth.

Pattern
📑 05

vs $log

Custom base next.

Related

❓ Frequently Asked Questions

$ln returns the natural logarithm of a number — the logarithm with base e (approximately 2.71828). It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $ln: <expression> }. The expression can be a field reference like "$value", a literal positive number, or another numeric expression.
$ln requires a positive number. ln(1) is 0. For null input, $ln returns null. Zero and negative numbers are not valid for natural logarithm and typically produce null or an error depending on context.
$ln computes the natural logarithm (base e). $log lets you specify a custom base as a second argument. Use $ln when you specifically need base-e logarithms.
Use $ln inside expression stages such as $project, $addFields, $set, and within other numeric expressions when transforming scientific, financial, or statistical data.

Continue the Operator Series

Move on to $log for logarithms with a custom base, or review $abs for absolute values.

Next: $log →

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