Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 70 ยท Query operators

Bitwise Query Operators

Query integer flag fields with $bitsAllSet, $bitsAnySet, $bitsAllClear and $bitsAnyClear, choose between bitmasks and bit positions, and set or clear bits with the $bit update operator.

Sometimes a whole set of yes/no facts is packed into one integer. A user's permissions might be stored as a number where bit 0 means "can read", bit 1 "can write" and bit 2 "can delete". The number 5 (binary 101) then means "read and delete, but not write". This flag field pattern is compact and common in systems that were ported from other databases, in feature-flag tables and in protocols.

MongoDB has four bitwise query operators for exactly this: they test which bits of a field are set (1) or clear (0). This lesson explains them, how to give the bit positions, what they match and do not match, and how to change individual bits with the $bit update operator. The mongosh blocks are real MongoDB syntax and cannot run on this page. The TryIts use a stand-in written in plain JavaScript with 64-bit BigInt arithmetic that follows the same rules; it is not a MongoDB server.

Bits and bit positions in a minute

A number is stored in binary. Bit positions are counted from the right, starting at 0 (the least significant bit):

Value Binary Bits that are set
1 0001 0
5 0101 0 and 2
6 0110 1 and 2
12 1100 2 and 3

Each bit has a weight: position 0 is worth 1, position 1 is worth 2, position 2 is worth 4, position 3 is worth 8, and so on. A field value of 6 therefore has bits 1 and 2 set because 2 + 4 = 6. If you design a flag field, give each flag its own power of two (1, 2, 4, 8, 16, ...), and never reuse or reorder them later.

The four operators

Operator Matches when the field has...
$bitsAllSet all of the given bits set to 1
$bitsAnySet at least one of the given bits set to 1
$bitsAllClear all of the given bits clear (0)
$bitsAnyClear at least one of the given bits clear (0)

Each takes the bits to test in one of three forms:

JavaScript
{ permissions: { $bitsAllSet: [0, 2] } }      // an array of bit positions
{ permissions: { $bitsAllSet: 5 } }           // a numeric bitmask (5 = bits 0 and 2)
{ permissions: { $bitsAllSet: BinData(0, "BQ==") } }   // a BinData bitmask, for very wide flag fields

The array of positions reads best, because the numbers are the bit indexes you care about, not a value you must compute. A numeric bitmask is shorter if you already have constants such as READ = 1, WRITE = 2, DELETE = 4. All three forms mean the same thing for the same bits.

Imagine a users collection where permissions holds the flags read = 1, write = 2, delete = 4, admin = 8:

JavaScript
db.users.insertMany([
  { name: "Ann", permissions: 1 },    // read
  { name: "Bob", permissions: 3 },    // read, write
  { name: "Cy",  permissions: 5 },    // read, delete
  { name: "Di",  permissions: 15 },   // everything
  { name: "Eli", permissions: 0 }     // nothing
])

db.users.find({ permissions: { $bitsAllSet: [0, 1] } })    // can read AND write: Bob, Di
db.users.find({ permissions: { $bitsAnySet: [2, 3] } })    // can delete OR admin: Cy, Di
db.users.find({ permissions: { $bitsAllClear: [2, 3] } })  // can neither delete nor admin: Ann, Bob, Eli
db.users.find({ permissions: { $bitsAnyClear: [0, 1] } })  // is missing read OR write: Ann, Cy, Eli

Try the four operators yourself. The stand-in below follows the real rules, including 64-bit two's complement for negative numbers. Change the masks and predict the result before you run it.

JS The four bitwise operators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows the edge cases. A string ("7"), a fractional number (5.5) and a missing field never match any bitwise operator. -1 matches because in 64-bit two's complement every bit is set, so -1 has bits 0 and 2 set (and every other bit too). 5.0 is a whole number, so it counts.

If you plan to query bit positions above 31 or 52, store the field as a 64-bit integer (Long) rather than a plain double: a double has 53 bits of precision, so very large flag values lose their low bits. See BSON Types for the numeric types.

Realistic uses

  • Permissions and feature flags: "all users who can write", "accounts with any beta flag".
  • Packed status fields imported from older systems or protocols, where one integer holds a dozen booleans.
  • Day-of-week masks: bit 0 is Monday ... bit 6 is Sunday, so $bitsAnySet: [5, 6] finds schedules that run on the weekend.

A caution: bitwise queries cannot use an index to narrow the search, so they scan. On a large collection, combine them with an indexed equality or range filter ({ tenantId: 7, permissions: { $bitsAllSet: [1] } }) so only a few documents are examined. If you query a flag all the time, store it as its own boolean field or an array of strings (roles: ["read", "write"]) and index that instead. Booleans are easier to read, easy to index, and every driver and dashboard understands them. Bitmasks win mainly when storage is extremely tight or the data model comes from elsewhere.

Changing bits: the $bit update operator

Reading flags is half the job. The $bit update operator changes a field with a bitwise and, or or xor, atomically on the server:

JavaScript
db.users.updateOne({ name: "Ann" }, { $bit: { permissions: { or: 2 } } })     // grant write: 1 | 2 = 3
db.users.updateOne({ name: "Bob" }, { $bit: { permissions: { and: ~2 } } })   // revoke write: 3 & ~2 = 1
db.users.updateOne({ name: "Cy" },  { $bit: { permissions: { xor: 4 } } })    // toggle delete: 5 ^ 4 = 1

Granting a flag is or with its mask. Revoking is and with the inverted mask (~2 in JavaScript). Toggling is xor. Because the update is atomic, two requests changing different bits of the same field do not overwrite each other, unlike a read-modify-write in application code. See Update Operators for the rest of the family. The second TryIt shows the arithmetic.

JS Grant, revoke and toggle flags with $bit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A field has the value 6 (binary 110). Which bit positions are set?

    6 = 2 + 4, so the bits with weights 2 and 4 are set: positions 1 and 2.
  2. 2. Which operator matches documents where at least one of the given bits is 1?

    $bitsAnySet needs just one of the listed bits to be set. $bitsAllSet needs all of them.
  3. 3. Does { flags: { $bitsAllSet: [0] } } match a document where flags is the string "1"?

    Strings, null, missing fields and numbers with a fractional part never match a bitwise operator.
  4. 4. How do you clear bit 1 (value 2) of a field with $bit?

    and with the inverted mask keeps every bit except bit 1. or sets bits; xor toggles them.
  5. 5. Why is a plain boolean field often better than a bitmask?

    Bitmasks save space but are cryptic and scan. Prefer booleans or arrays when you query the flags often.

Summary

  • Bit positions count from 0 at the right; a flag field gives each flag its own power of two.
  • $bitsAllSet, $bitsAnySet, $bitsAllClear and $bitsAnyClear test a field against bit positions (array), a numeric bitmask, or a BinData mask.
  • Only whole numbers match; strings, null, missing fields and fractions never do, and negative numbers use 64-bit two's complement.
  • Bitwise queries cannot use an index to narrow results, so combine them with an indexed filter, or model queried flags as booleans or arrays.
  • The $bit update operator sets (or), clears (and with an inverted mask) or toggles (xor) bits atomically.

Next, return to the field-existence operators in Element and Evaluation Operators.