How to toggle a boolean field in one document with atomic operation?


Is there any way to toggle the boolean field of ONE document in MongoDB with atomic operation? Say, (In python)

cl.update({"_id": ...}, {"$toggle": {"field": 1}})
By : halfjuice


The SERVER-4362 issue is actually resolved now and you have the $bit update operator available. So along with it's xor argument you can now do this in an atomic action:

  { "_id": ...}, 
     "$bit": { 
         "field": { "xor": NumberInt(1) } 
  { "returnNewDocument": true, "upsert": true }

So as long as the value of field is kept at 0 or 1 then a bitwise "flip" will result that makes the current value the opposite of what it was at the time of the modification.

The .findOneAndUpdate() is not required, but just a way of demonstrating that the resulting value is different on every modification.

By : Neil Lunn

This video can help you solving your question :)
By: admin