$bitXor (Bitwise XOR)
Last updated: 2026-10-09
$bitXor (Bitwise XOR)
$bitXor performs a bitwise XOR on integers. Available since MongoDB 6.3, it accepts an array of integers (or a single number). XOR yields 1 where bits differ and 0 where they match, making it useful for checksums, bit flipping, and lightweight obfuscation, such as XORing a value with a key. Any null or missing argument yields null; operands must be int32 or int64. Note that XORing the same value twice restores the original, a classic use of its reversibility.
| Category | Math |
|---|---|
| MongoDB Version | 6.3+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $bitXor: [ <integer1>, <integer2>, ... ] }
⚙️ Parameters
| integer | int32 or int64 integers, or expressions resolving to them; at least two. |
|---|
Returns:The bitwise XOR of all operands; null when null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $bitXor: flip the low 8 bits with 255
db.users.aggregate([
{ $project: {
masked: { $bitXor: ['$score', 255] }
} }
])
Output:
{ '_id': 1, 'masked': 200 }
{ '_id': 2, 'masked': 155 }
📌 Notes
- Matching bits give 0 and differing bits give 1
- XORing the same value twice restores the original, enabling reversible tricks
- Only int32 and int64 are supported
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the rule of $bitXor?
ASame bits yield 0 and different bits yield 1; for example, 5 XOR 3 is 6.
QWhat can $bitXor be used for?
ABit flipping, simple checksums, and lightweight obfuscation.
QWhy does XORing twice restore the value?
AXOR is self-inverse: x XOR k XOR k always equals x.