MongoDB Bitwise Update Operator

How to use the new bitwise update operator introduced in MongoDB 2.6

Recently I came across a requirement to toggle boolean values in documents. Since MongoDB version 2.6 we can use the new bitwise update operator and accomplish such tasks in a single operation.

Use Case

We have documents which describe sensors which can be enabled and disabled. Sensors are part of a specific group. To be able to make use of the bitwise update operator we use an integer field to represent the enabled state (1 for on, 0 for off):

  "_id": "100",
  "group": 200,
  "name", "Sensor 100",
  "enabled": 0,

Let's assume we want to toggle the state of all sensors in group 200. It is as easy as this:

  { "group": 200 }, 
  { "$bit": { "enabled": { "xor": NumberInt(1) } } }

On each execution of this update statement the value of enabled of all sensors in the group will be toggled.

For comments and questions, please use Twitter mentioning @sebastian_voss