Mohamed El Ghamry
Mohamed El Ghamry

Reputation: 23

Decrementing a field of type number in mongodb and nodejs

I'm learning mongodb. I have a collection called item which has a field piecesLeft of a type Number, and I want to decrement this field value when a user orders this particular item. Any help?

Upvotes: 0

Views: 794

Answers (1)

Lemix
Lemix

Reputation: 2930

Use $inc operator.

 db.yourcollection.update({ /* find options */ }, { $inc: {piecesLeft : -1 } });

Updated:

db.yourcollection.update({
    _id: '572f16440a0dbb1e0cc02201', // Find updated item e.g. by _id
    piecesLeft: { $gt: 0 } // Update only if piecesLeft > 0
}, {
    $inc: {
        piecesLeft: -1 // Increment by -1 
    }
});

Upvotes: 3

Related Questions