$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.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

numeric valueA positive numeric expression to take the logarithm of.
baseThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏