$bit (Bitwise Update)

Last updated: 2026-10-09

$bit (Bitwise Update)

$bit performs bitwise operations on integer fields: AND, OR, XOR. `{ $bit: { flags: { and: 254 } } }` clears the lowest bit. It is atomic and, unlike most update operators, does not create a missing field — it throws instead. Ideal for compact bitmask permissions and flags, complementing the $bits* query operators.

CategoryUpdate Array
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $bit: { <field>: { and: <value> | or: <value> | xor: <value> } } }

⚙️ Parameters

fieldThe integer field to apply bitwise ops to.
bitwise operationOne of and, or, xor with a bitmask value.

Returns:The update result

▶ Example

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

// $bit: AND to clear the lowest bit
// 254 in binary is 11111110
db.users.updateOne(
  { _id: 1 },
  { $bit: { flags: { and: 254 } } }
)

// OR to set bit 0
db.users.updateOne(
  { _id: 1 },
  { $bit: { flags: { or: 1 } } }
)

Output:

// The lowest bit is cleared; the second example sets bit 0

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhich operations does $bit support?
AAND, OR and XOR.
QWhat happens if the $bit field is missing?
AIt throws instead of creating; initialize with $set first.
QHow do I set or clear a single bit?
ASet with or: 1 shifted left n; clear with and: the bitwise NOT of that.
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%

🙏 帮我们做得更好

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

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