Database
NoSQL
MongoDB
Operators
Bitwise Query Operators

Bitwise Query Operators in MongoDB

Bitwise query operators in MongoDB are used to perform bitwise operations on numeric fields. They help in querying documents based on the state of specific bits within a field. Here’s a detailed look at each of these operators:

$bitsAllClear

Definition: The $bitsAllClear operator checks whether all specified bits in a field are clear (i.e., not set).

Use Case: This operator is useful when you want to ensure that certain bits are not set in a field, such as verifying that specific flags are not active.

db.documents.find({
  flags: { $bitsAllClear: 3 } // Binary 11 (bits 1 and 2)
});

$bitsAllSet

Definition: The $bitsAllSet operator checks whether all specified bits in a field are set.

Use Case: This operator is helpful when you want to ensure that specific bits are active, such as confirming that certain flags are turned on.

db.documents.find({
  flags: { $bitsAllSet: 3 } // Binary 11 (bits 1 and 2)
});

$bitsAnyClear

Definition: The $bitsAnyClear operator checks whether at least one of the specified bits in a field is clear.

Use Case: This operator is useful when you want to find documents where at least one of several bits is not active, such as checking if any of several flags are turned off.

db.documents.find({
  flags: { $bitsAnyClear: 3 } // Binary 11 (bits 1 and 2)
});

$bitsAnySet

Definition: The $bitsAnySet operator checks whether at least one of the specified bits in a field is set.

Use Case: This operator helps in finding documents where at least one of several bits is set, such as confirming that at least one of several flags is turned on.

db.documents.find({
  flags: { $bitsAnySet: 3 } // Binary 11 (bits 1 and 2)
});

These operators allow for detailed and efficient bitwise querying, which is particularly useful for scenarios where binary flags or status indicators are used within documents.