Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Toggle" query in MongoDB [duplicate]

Tags:

mongodb

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?

like image 501
Fabio B. Avatar asked Sep 23 '12 17:09

Fabio B.


People also ask

How do I toggle values in MongoDB?

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.

Is the command in MongoDB that is equivalent of SQL's truncate?

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.

What are modifiers in MongoDB?

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.

How use MongoDB $set?

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.


1 Answers

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.

like image 181
Eve Freeman Avatar answered Oct 07 '22 13:10

Eve Freeman