$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.
| Category | Update Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $bit: { <field>: { and: <value> | or: <value> | xor: <value> } } }
⚙️ Parameters
| field | The integer field to apply bitwise ops to. |
|---|---|
| bitwise operation | One 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
- Supports and, or and xor
- Does not create a missing field — it throws
- Integers only (int, long)
🏷️ Related Tags
💡 Related Cases
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.