$bit
Definition
$bit
- The
$bit
operator performs a bitwise update of a field.The operator supports bitwiseand
, bitwiseor
, and bitwisexor
(i.e. exclusive or) operations. Tospecify a$bit
operator expression, use the followingprototype:
- { $bit: { <field>: { <and|or|xor>: <int> } } }
Only use this operator with integer fields (either 32-bit integer or64-bit integer).
To specify a <field>
in an embedded document or in an array, usedot notation.
Note
All numbers in the mongo
shell are doubles, notintegers. Use the NumberInt()
or the NumberLong()
constructor to specify integers. See NumberInt orNumberLong for more information.
Examples
Bitwise AND
Consider the following document inserted into the collectionswitches
:
- { _id: 1, expdata: NumberInt(13) }
The following update()
operation updates theexpdata
field to the result of a bitwise and
operation betweenthe current value NumberInt(13)
(i.e. 1101
) andNumberInt(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
.
Bitwise OR
Consider the following document inserted into the collectionswitches
:
- { _id: 2, expdata: NumberLong(3) }
The following update()
operation updates theexpdata
field to the result of a bitwise or
operation betweenthe current value NumberLong(3)
(i.e. 0011
) andNumberInt(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) }
Bitwise XOR
Consider the following document in the collection switches
:
- { _id: 3, expdata: NumberLong(1) }
The following update()
operation updates theexpdata
field to the result of a bitwise xor
operation betweenthe current value NumberLong(1)
(i.e. 0001
) andNumberInt(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) }
See also