Possible Duplicate:
In MongoDB, How to toggle a boolean field in one document with atomic operation?
I need to update a document value, “toggling” it:
The collection is “Comment” which has boolean flag “isAdmin”.
I’m going to update a given comment id, setting isAdmin false if it’s true and viceversa.
However this does not work:
db.comments.update( { "id": "xxx" }, { $set: { isAdmin: $not isAdmin } } );
What’s the right syntax?
You can’t reference the document you find in an update like that. You’ll need to do a query to find the document, and then do an update after you know what the value is. Two step process:
Update:
This answer has been out of date for a while (since 2.5.2):
https://jira.mongodb.org/browse/SERVER-4362
It is now possible via the
$bitoperatorxor, and usingfindOneAndUpdateto avoid two separate commands.