0

When working on MySQL, I can setup an UPDATE based on the current value of the field as such:

UPDATE table SET field = field + 1;

Or

UPDATE table SET field = IF(field == 1, 0, 1);

I'm trying to figure out how I can do something similar in Mongo. If I want to do something like an if or trinary operator, can I do that in Mongo?

Rohit
  • 3,018
  • 2
  • 29
  • 58

1 Answers1

0

Use $inc for incremental updates

db.update({}, {$inc: { field: 1 }}, {multi: true});

For a ternary operator in your example you can use $bit, however it is a hurdle to access data from document during update

db.update({}, {$bit: { field: {xor: 1} }}, {multi: true});
Lilly
  • 28
  • 4
  • Interesting. I knew about increment, so that was a poor example for me to make; I was more curious about how to alter fields based on their existing values. I see that's harder to do than expected. – Rohit Jun 27 '15 at 20:32
  • 1
    You will have to iterate on each document.Mongo does allow to do that server side. – Lilly Jun 28 '15 at 01:03
  • a generic solution would be smth like this http://stackoverflow.com/a/3792958/5051250 – Lilly Jun 28 '15 at 01:05