$log2 (Base-2 Log)

Last updated: 2026-10-09

$log2 (Base-2 Log)

$log2 returns the base-2 logarithm of a number, used in computing contexts such as binary-search depth, binary-tree height, or bit-width estimation, for example how many bits a number needs. A null or missing argument yields null; the input must be positive — zero or negative values return null. It is a special case of $log with a fixed base of 2, keeping code concise. $log2 inverts powers of two, making it the counterpart of $pow: [2, x].

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $log2: <numeric-expression> }

⚙️ Parameters

numeric valueA numeric value or an expression resolving to one; must be greater than 0.

Returns:The base-2 logarithm of the input; null for non-positive, null, or missing input

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $log2: estimate how many binary bits an integer needs
db.numbers.aggregate([
  { $project: {
      bits: { $ceil: { $add: [{ $log2: '$value' }, 1] } }
  } }
])

Output:

{ '_id': 1, 'bits': 10 }
{ '_id': 2, 'bits': 8 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhen would I use $log2?
ABinary search, binary-tree depth, and bit-width estimation.
QWhat is $log2(1024)?
AIt is 10, since 2 raised to the power of 10 is 1024.
QHow are $log2 and $pow related?
AThey are inverses: $pow: [2, x] computes 2 to the power of x and $log2 goes back.
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%

🙏 帮我们做得更好

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

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