Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

$bit

On this page

  • Definition
  • Behavior
  • Examples
$bit

The $bit operator performs a bitwise update of a field. The operator supports bitwise and, bitwise or, and bitwise xor (i.e. exclusive or) operations. To specify a $bit operator expression, use the following prototype:

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

Only use this operator with integer fields (either 32-bit integer or 64-bit integer).

To specify a <field> in an embedded document or in an array, use dot notation.

Note

All numbers in the mongo shell are doubles, not integers. Use the NumberInt() or the NumberLong() constructor to specify integers. See NumberInt or NumberLong for more information.

In MongoDB 4.4 and earlier, update operators process document fields in lexicographic order. See Update Operators Behavior for details.

Consider the following document inserted into the collection switches:

{ _id: 1, expdata: NumberInt(13) }

The following update() operation updates the expdata field to the result of a bitwise and operation between the current value NumberInt(13) (i.e. 1101) and NumberInt(10) (i.e. 1010):

db.switches.update(
{ _id: 1 },
{ $bit: { expdata: { and: NumberInt(10) } } }
)

The bitwise and operation results in the integer 8 (i.e. 1000):

1101
1010
----
1000

And the updated document has the following value for expdata:

{ "_id" : 1, "expdata" : 8 }

The mongo shell displays NumberInt(8) as 8.

Consider the following document inserted into the collection switches:

{ _id: 2, expdata: NumberLong(3) }

The following update() operation updates the expdata field to the result of a bitwise or operation between the current value NumberLong(3) (i.e. 0011) and NumberInt(5) (i.e. 0101):

db.switches.update(
{ _id: 2 },
{ $bit: { expdata: { or: NumberInt(5) } } }
)

The bitwise or operation results in the integer 7 (i.e. 0111):

0011
0101
----
0111

And the updated document has the following value for expdata:

{ "_id" : 2, "expdata" : NumberLong(7) }

Consider the following document in the collection switches:

{ _id: 3, expdata: NumberLong(1) }

The following update() operation updates the expdata field to the result of a bitwise xor operation between the current value NumberLong(1) (i.e. 0001) and NumberInt(5) (i.e. 0101):

db.switches.update(
{ _id: 3 },
{ $bit: { expdata: { xor: NumberInt(5) } } }
)

The bitwise xor operation results in the integer 4:

0001
0101
----
0100

And the updated document has the following value for expdata:

{ "_id" : 3, "expdata" : NumberLong(4) }

Tip

See also:

← Bitwise Update Operator