仅在mongodb中更新字段,如果它小于另一个字段

时间:2015-02-21 13:19:48

标签: mongodb meteor

我目前有以下查询:

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

但我想做以下事情:

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

如果maxenergy是文档中的另一个字段,这是可能的还是我需要遍历整个集合来执行此操作?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用$where运算符:

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

这与已经问过here的问题类似。 但要小心,因为JavaScript必须在服务器端执行,所以它可能会非常慢,具体取决于您的集合大小。