集合中的值递减到0

decrement value in collection until 0

本文关键字:集合      更新时间:2023-09-26

我使用meteorJS,并有一个user collection,我在用户配置文件中存储了一个名为'score'的值。

现在,我想以每个用户的分数值递减10来更新集合,但是我在获取每个用户的分数值并像"current value - 10"一样更新它们时遇到了问题。它还应该只更新不低于0的值。

有人能给我一个提示如何查找和更新每个用户配置文件的值吗?

Meteor.users.update({'profile.score': {$gte: 10}}, {$inc: {'profile.score': -10}}, {multi: true});

这是否完成了您所需要的?根据需要更改选择器

说明:我们过滤掉得分在10分以上的用户。我们将所有匹配用户的分数"增加"-10(因此我们将其减少10)。

这里的基本过程是使用 $inc 更新操作符,但是当然有0作为下限值的治理。因此,您可以接受:

Users.update({ "_id": userId },{ "$inc": { "score": -10 } });
Users.update(
    { "_id": userId, "score": { "$lt": 0 } },
    { "$set": { "score": 0 } }
);

如"两个"操作和连接所示。或者你可以用MongoDB的批量操作API来获得更花哨的Meteor方法:

Meteor.methods(
    "alterUserScore": function(userId,amount) {
        var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
        var bulk = db.collection('users').inititializeOrderedBulkOp();
        bulk.find({ "_id": userId }).updateOne({ "$inc": { "score": amount } });
        bulk.find({ "_id": userId, "score": { "$lt": 0 } }).updateOne({
            "$set": { "score": 0 }
        });
        bulk.execute(
            Meteor.bindEnvironment(
                function(err,result) {
                    // maybe do something here
                },
                function(error) {
                    // report real bad here
                }
            )
        );
    }
);

在"服务器"请求上的优点是,即使它仍然是"两个"更新操作,服务器的实际请求和响应只有"一个"请求和"一个"响应。所以这比两次往返要有效率得多。特别是当从浏览器客户端发起时。

如果你不这样做,那么你可能会错过一些事情,比如当当前值是6,你想把它减小到0。在此条件下,$gt将失败。

您可以尝试将其作为Schema。

const Customer = new Schema({
  cash: {
    type: Number,
    min: 0
  }
});