$ln is a MongoDB aggregation expression that returns the natural logarithm of a number—log base e (about 2.71828). The input must be a positive number.
Remember
$ln = Math.log for aggregation (base e)
{ $ln: <expression> }
ln(1) → 0
ln(e) → 1
input → must be > 0
null / missing → null
0 or negative → error
inverse → $exp
for each document:
x = evaluate(expression)
if x is null or missing:
result = null
else if x <= 0:
error // natural log undefined
else:
result = ln(x) // base e
emit { ..., field: result }
Reference
Cheat Sheet
Keep these facts handy while using natural logs in pipelines.
Topic
Detail
Type
Aggregation expression (not a find filter)
Syntax
{ $ln: <expression> }
Base
Always e ≈ 2.71828
vs $log
$log chooses the base
Domain
Input must be > 0
Handy values
ln(1)=0 · ln(e)≈1
Inverse
$exp
Try it
Live Preview
Watch $ln on common positive values. Zero and negatives are invalid.
We use one sample value equal to Math.E. First insert it, then compute $ln, then show ln(1) beside it. Run these in mongosh after inserting the sample data once.
Example 1 — Sample Data
Imagine one measurement whose value is e ((Math.E ≈ 2.71828). We save it in a collection named samples.
ln(e) is exactly 1 in theory; other inputs return floats. Round only when your report needs fixed decimals.
Analysis
Performance Notes
Approach
Cost
Best for
$ln per document
Cheap math
On-the-fly transforms
Filter then $ln
Fewer docs
Dirty or sparse data
Store log on write
No recompute
Hot dashboards
Natural log is inexpensive. Filter invalid or unused documents early with $match when only some rows need a log.
Remember
Key Takeaways
Role: natural logarithm (base e).
Domain: input must be > 0.
vs $log:$ln is fixed base e; $log chooses a base.
Sample:ln(e) → 1, ln(1) → 0.
One line:$ln answers “what power of e gives this number?”—for positive inputs only.
Frequently Asked Questions
$ln returns the natural logarithm of a number—the logarithm with base e (about 2.71828). Use it inside aggregation stages such as $project and $addFields.
Use { $ln: <expression> }. Pass a field like "$value", a positive number literal, or any expression that resolves to a positive number.
$ln needs a positive number. ln(1) is 0 and ln(e) is about 1. Null or missing input returns null. Zero or negative values cause an error.
$ln is always base e. $log lets you choose a base as a second argument. Use $ln when you specifically need the natural log.
Use $exp. If y = $ln(x), then $exp(y) returns x (for valid positive x).
Anywhere an aggregation expression is allowed—$addFields, $project, $set, and inside other numeric expressions.