decrement value in collection until 0

10,677

Solution 1

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

Does this accomplish what you need? Change selector as needed.

Explanation: We filter out users who have a score of 10 or more. We "increase" all of the matching users' scores by -10 (so we decrease them by 10).

Solution 2

The basic process here is to use the $inc update operator, but of course there is the governance of 0 as a floor value. So you can therefore either accept:

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

As "two" operations and connections as shown. Or you can get fancier in Meteor methods with the Bulk Operations API of MongoDB:

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

The advantage there on the "server" request is that even though it is still "two" update operations, the actual request and response from the server is only "one" request and "one" response. So this is a lot more efficient than two round trips. Especially if intitiated from the browser client.

If you did otherwise, then you likely miss things such as when the current value is 6 and you want to decrease that to 0. A $gt in the condition will fail there.

Solution 3

You can try this as the Schema instead.

const Customer = new Schema({
  cash: {
    type: Number,
    min: 0
  }
});
Share:
10,677
Dude
Author by

Dude

:)

Updated on June 09, 2022

Comments

  • Dude
    Dude almost 2 years

    I´m using meteorJS and have a user collection where I´ve stored a value called 'score' in the users profile.

    Now, I want to update the collection with a decrement of the score value by 10 for each user but I have problems with getting the score value for each user and update them like "current value - 10". It also should only update the values that will not become lower than 0.

    Can someone give me a hint how to find and update the value for each user the profile?

  • user728291
    user728291 almost 9 years
    Your explanation is incorrect and only one user will be updated. You need to pass the option {multi : true} to change more than one.
  • Oskar
    Oskar almost 9 years
    @user728291 Thanks for the correction. I missed that.
  • mohamnag
    mohamnag almost 3 years
    given a score of for example 15, it will never reach 0. I believe this answer is only correct if you consider score to be only a factor of 10.