$bitsAllSet as bitwise query operator

APPLIES TO: MongoDB vCore

The $bitsAllSet operator is used to match documents where all the specified bit positions are set (that is, are 1). This operator is useful for performing bitwise operations on fields that store integer values. It can be used in scenarios where you need to filter documents based on specific bits being set within an integer field.

Syntax

{
  <field>: { $bitsAllSet: <bitmask> }
}
  • <field>: The field in the document on which the bitwise operation is to be performed.
  • <bitmask>: A bitmask indicating which bits must be set in the field's value.

Example

Consider a collection named stores that contains documents with various fields. To find documents where the storeId field has specific bits set, you can use the $bitsAllSet operator.

Example 1: Find stores with specific bits set in storeId

db.stores.find({
  "store.storeId": { $bitsAllSet: 0b00000011 }
})

This query would return documents where the storeId field has both the first and second bits set.

Example 2: Find stores with specific bits set in totalStaff.fullTime

db.stores.find({
  "store.staff.totalStaff.fullTime": { $bitsAllSet: 0b00001111 }
})

This query would return documents where the fullTime field in totalStaff has the first 4 bits set.