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?
If you are using MongoDB 4.2, you can use aggregation operators in your update statement, like: . findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]); That will set present to true if it is false, and to false if it is any other value.
Remove All Documents If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.
If you use $each modifier with $addToSet operator, then it adds multiple values to an array field if the specified value does not present in the array field. If you use $each modifier with $push operator, then it appends multiple values to an array field.
The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
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:
var doc = db.comments.findOne({id:"xxx"});
db.comments.update({id:"xxx"}, {$set: {isAdmin: !doc.isAdmin}});
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 $bit
operator xor
, and using findOneAndUpdate
to avoid two separate commands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With