$bitNot (Bitwise NOT)
Last updated: 2026-10-09
$bitNot (Bitwise NOT)
$bitNot performs a bitwise NOT (two's complement) on a single integer — the only bitwise operator that takes one operand. Available since MongoDB 6.3, the result equals -x-1, so NOT 5 gives -6. It is used to build complementary masks and general negation in bit math. A null or missing argument yields null; the operand must be int32 or int64. Note the sign flips: this is two's complement, not a plain inversion of magnitude.
| Category | Math |
|---|---|
| MongoDB Version | 6.3+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $bitNot: <integer-expression> }
⚙️ Parameters
| integer | An int32 or int64 integer, or an expression resolving to one. |
|---|
Returns:The bitwise NOT of the input (-x-1); null when null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $bitNot: invert permission bits to build an exclusion mask
db.users.aggregate([
{ $project: {
denied: { $bitNot: '$allowedBits' }
} }
])
Output:
{ '_id': 1, 'denied': -6 }
{ '_id': 2, 'denied': -1 }
📌 Notes
- The result is two's-complement NOT, equal to -x-1
- It accepts exactly one operand
- Only int32 and int64 are supported
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is $bitNot(5)?
AIt is -6, since two's-complement NOT follows -x-1.
QWhy does $bitNot produce negative results?
ATwo's-complement NOT flips the high bit, changing the sign.
QWhere is $bitNot useful?
ABuilding complementary masks or composing with other bitwise operators.