$bit

Definition

  • $bit
  • The $bit operator performs a bitwise update of a field.The operator supports bitwise and, bitwiseor, and bitwise xor (i.e. exclusive or) operations. Tospecify a $bit operator expression, use the followingprototype:
  1. { $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:

  1. { _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):

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

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

  1. 1101
  2. 1010
  3. ----
  4. 1000

And the updated document has the following value for expdata:

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

The mongo shell displays NumberInt(8) as 8.

Bitwise OR

Consider the following document inserted into the collectionswitches:

  1. { _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):

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

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

  1. 0011
  2. 0101
  3. ----
  4. 0111

And the updated document has the following value for expdata:

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

Bitwise XOR

Consider the following document in the collection switches:

  1. { _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):

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

The bitwise xor operation results in the integer 4:

  1. 0001
  2. 0101
  3. ----
  4. 0100

And the updated document has the following value for expdata:

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

See also

db.collection.update(),db.collection.findAndModify()