$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].
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $log2: <numeric-expression> }
⚙️ Parameters
| numeric value | A 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
- The base is fixed at 2, equivalent to $log: [x, 2]
- The input must be greater than 0; zero or negative values return null
- It inverts $pow with a base of 2
🏷️ Related Tags
💡 Related Cases
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.