Kobe Janssens
Kobe Janssens

Reputation: 318

MongoDB - Is it possible to when updating a value just count up 1 to the current value?

Is it possible to when updating a value just count up 1 to the current value? Probably it's possible to first read the value and then just add up 1 but isn't there another (more efficient) way? I'm using the pymongo connector.

Example record:
{"productId": "125", "value": 5.99, "amount": 50}

Code:

searchQuery = {"productId": "125"}
newValues = { "$set": { "amount": +1 } } # Add 1 to the amount
mycol.update_one(searchQuery, newvalues)

Upvotes: 0

Views: 43

Answers (1)

Belly Buster
Belly Buster

Reputation: 8834

Your way would just set amount to 1 every time regardless; what you need is:

mycol.update_one(searchQuery, { '$inc': { 'amount': 1 }})

Upvotes: 1

Related Questions