user2950509
user2950509

Reputation: 1057

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 }}

Upvotes: 5

Views: 633

Answers (3)

Carlos Saltos
Carlos Saltos

Reputation: 1511

Yes, it's possible to do that with MongoDB, of course !! ... just use the find's forEach feature like this:

db.collection("bugs").find({ _id: searchId }).forEach(function(bugDoc) { 
  db.collection("bugs").updateOne({ _id: searchId }, { $set: { "fixed": !bugDoc.fixed }});
});

NOTE: bugDoc contains all the fields of the original document and you can make all the calculations and changes you want in this double operation update

Upvotes: 0

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8162

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.

Upvotes: 4

mbuechmann
mbuechmann

Reputation: 5780

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 } }

Upvotes: 3

Related Questions