What if you could update scores instantly without risking mistakes or delays?
Why $inc operator for incrementing in MongoDB? - Purpose & Use Cases
Imagine you have a list of scores for players in a game stored on paper. Every time a player scores, you have to find their name and add the new points manually.
This manual method is slow and easy to mess up. You might add points to the wrong player or forget to update the score. It's hard to keep track when many players score quickly.
The $inc operator in MongoDB lets you add a number directly to a field in the database. It updates the score safely and instantly without needing to read the old value first.
oldScore = db.players.findOne({name: 'Alice'}).score
newScore = oldScore + 5
db.players.updateOne({name: 'Alice'}, {$set: {score: newScore}})db.players.updateOne({name: 'Alice'}, {$inc: {score: 5}})You can quickly and safely update numbers in your database with a single command, even when many users change data at the same time.
In a social media app, $inc can instantly increase the number of likes on a post whenever someone clicks the like button, without losing any clicks.
Manual updates are slow and error-prone.
$inc updates numbers directly and safely.
This makes real-time counting and scoring easy and reliable.