Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decrement value in collection until 0

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?

like image 944
Dude Avatar asked Aug 03 '15 13:08

Dude


3 Answers

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).

like image 128
Oskar Avatar answered Nov 20 '22 11:11

Oskar


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.

like image 33
Blakes Seven Avatar answered Nov 20 '22 12:11

Blakes Seven


You can try this as the Schema instead.

const Customer = new Schema({
  cash: {
    type: Number,
    min: 0
  }
});
like image 2
Ritwik Avatar answered Nov 20 '22 10:11

Ritwik