0

I currently have the following query:

Meteor.users.update({energy: {$lt: 30}}, {$inc: {"energy": 1}}, {multi: true});

But I want to do the following:

Meteor.users.update({energy: {$lt: maxenergy}}, {$inc: {"energy": 1}}, {{multi: true});

Where maxenergy is another field in the document, is this possible or do I need to loop over the entire collection to do this?

Any help would be appreciated.

AliceDTRH
  • 77
  • 10
  • You could flip this around and make the field something like `energyLost`. Then decrement it for documents where it's greater than 0. – sbking Feb 21 '15 at 13:32
  • not sure I understand "another field in the collection" - do you mean in the same document, or do you mean sth. like max(energy) in all the collection? – mnemosyn Feb 21 '15 at 13:41
  • Well, every user has a field called energy and a field called maxenergy. I want to update energy only if energy is less than maxenergy. – AliceDTRH Feb 21 '15 at 13:46
  • I changed the question to say document instead of collection, since that seems to be the proper term? – AliceDTRH Feb 21 '15 at 14:06

1 Answers1

1

You can use the $where operator for that:

Meteor.users.update(
    {$where : "this.energy < this.otherFieldName"},
    {$inc: {"energy": 1}},
    {multi: true}
);

It's a similar problem to the one already asked here. Be careful though, since the JavaScript has to be executed on the server side it can be quite slow, depending on your collection size.

Community
  • 1
  • 1
joao
  • 4,067
  • 3
  • 33
  • 37
  • Thank you for the answer! I did look on Google and searched on stackoverflow, but I couldn't find the answer with the terms I used. – AliceDTRH Feb 21 '15 at 13:53