Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update MongoDB document based on its previous values?

Sorry if this is pretty basic, but I'm a mongodb newbie and haven't been able to find an answer to this:

Let's say I'm doing the following:

db.collection("bugs").updateOne({ _id: searchId }, { $set: { "fixed": true }}

How to set "fixed" to the contrary of whatever the last value of "fixed" was? Without any additional queries? Something like { $set: { "fixed": !fixed }}

like image 904
user2950509 Avatar asked Jul 13 '18 15:07

user2950509


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

What is Upsert in update MongoDB?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.

How do I Upsert in MongoDB?

Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.

Which operator is used to update specific fields in MongoDB?

Comparing values (or numbers) using $max operator: Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 40000.


2 Answers

It is not really possible to achieve this in MongoDB as of now in just one operation by sticking to the idea of storing boolean values (might be possible in future versions of MongoDB). But, there is a workaround to do this by storing bits (0 or 1) to represent true or false instead of boolean values and performing bitwise xor operation on those in MongoDB as follows:

db.collection("bugs").updateOne(
  {
    _id: searchId
  },
  { 
    $bit : {
     fixed: {
       xor: NumberInt(1)
     }
    }
  }
)

Please note that you also have to store 0 as NumberInt(0) to represent false and 1 as NumberInt(1) to represent true in the fixed prop as MongoDB by default treats all numbers as floating-point values.

like image 78
UtkarshPramodGupta Avatar answered Sep 19 '22 22:09

UtkarshPramodGupta


This is not possible in MongoDB. You have to retrieve the doc from the db and then update it:

var doc = db.collection("bugs").findOne({ _id: searchId });
db.collection("bugs").updateOne({ _id: searchId }, { $set: { "fixed": !doc.fixed } }
like image 42
mbuechmann Avatar answered Sep 20 '22 22:09

mbuechmann