$log (Logarithm)
Last updated: 2026-10-09
$log (Logarithm)
$log returns the logarithm of a number with a specified base. It takes two arguments: the value and the base. Unlike $ln, $log10, and $log2, the base is given by the second argument, so $log: [8, 2] returns 3. It covers custom-base logarithm needs. Both the value and the base must be greater than 0, and the base must not equal 1; any null or missing argument yields null. When the base is exactly 10 or 2, prefer $log10 or $log2 for clarity.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $log: [ <value>, <base> ] }
⚙️ Parameters
| numeric value | A positive numeric expression to take the logarithm of. |
|---|---|
| base | The logarithm base; must be greater than 0 and not equal to 1. |
Returns:The logarithm with the given base; null for invalid, null, or missing arguments
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $log: logarithm with base 2
db.sales.aggregate([
{ $project: {
log2x: { $log: ['$amount', 2] }
} }
])
Output:
{ '_id': 1, 'log2x': 6.643856189774724 }
{ '_id': 2, 'log2x': 4.321928094887363 }
📌 Notes
- Both the value and the base must be greater than 0, and the base cannot be 1
- For bases 10 and 2, $log10 and $log2 read better
- Invalid or missing arguments return null rather than throwing
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do I specify the base for $log?
AThe second argument is the base, so $log: [8, 2] returns 3.
QCan the base of $log be 1?
ANo — base 1 makes the logarithm undefined and returns null.
QHow do $log and $ln differ?
A$log takes a configurable base while $ln is fixed to base e.