- Reference >
- Operators >
- Update Operators >
- Bitwise Update Operator >
- $bit
$bit¶
On this page
Definition¶
-
$bit¶ The
$bitoperator performs a bitwise update of a field. The operator supports bitwiseand, bitwiseor, and bitwisexor(i.e. exclusive or) operations. To specify a$bitoperator expression, use the following prototype: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
mongoshare doubles, not integers. Use theNumberInt()or theNumberLong()constructor to specify integers. See NumberInt or NumberLong for more information.
Behavior¶
Starting in MongoDB 5.0, mongod no longer raises an
error when you use an update operator like $bit
with an empty operand expression ( { } ). An empty update results
in no changes and no oplog entry is created (meaning that the
operation is a no-op).
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.
Examples¶
The following examples use the switches collection:
Bitwise AND¶
Use a bitwise and in the updateOne()
operation to update expdata.
The bitwise and operation:
- gets the bitwise value of
expdata - uses
andto apply the bitwise value of Int32(10) - updates
expdatawith the result, 1000
Binary 1000 is equivalent to Int32(8). The
db.switches.find( { _id: 1 } ) command returns the following
document:
Bitwise OR¶
Use a bitwise or in the updateOne()
operation to update expdata.
The bitwise or operation:
- gets the bitwise value of
expdata - uses
orto apply the bitwise value of Int32(5) - updates
expdatawith the result, 0111
Binary 0111 is equivalent to Int32(7). The
db.switches.find( { _id: 2 } ) command returns the following
document:
Bitwise XOR¶
Use a bitwise xor in the updateOne()
operation to update expdata.
The bitwise and operation:
- gets the bitwise value of
expdata - uses
andto apply the bitwise value of Int32(5) - updates
expdatawith the result, 0100
Binary 0100 is equivalent to Int32(4). The
db.switches.find( { _id: 3 } ) command returns the following
document: