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

CategoryMath
MongoDB Version6.3+
Example Languagemongosh (Shell)

📝 Syntax

{ $bitXor: [ <integer1>, <integer2>, ... ] }

⚙️ Parameters

integerint32 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

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

🙏 帮我们做得更好

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

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