HoneyPoop
HoneyPoop

Reputation: 513

Update field instead of add to a field pymongo

Whenever I try to update a field, it ends up adding the number to the field instead of replacing it. For example:

db.test.update_one({"_id": 0}, {'$inc': {"time": 2}})

If there were already 1 in the field time, the field time would update to 3 instead of 2. Can anyone help with this?

Upvotes: 0

Views: 391

Answers (1)

prasad_
prasad_

Reputation: 14287

import pymongo
client = pymongo.MongoClient()
collection = client.testdb.test

print(collection.find_one())    # 'time': 1

collection.update_one( { '_id': 0 }, { '$set': { 'time': 3 } } )
print(collection.find_one())    #  'time': 4

collection.update_one( { '_id': 0 }, { '$inc': { 'time': 1 } } )
print(collection.find_one())    #  'time': 5

MongoDB document data can be updated with the update_one method. You can use different update operators for different update operations, e.g., $set, $inc, $unset, etc.

  • $inc Increments the value of the field by the specified amount.
  • $set Sets the value of a field in a document.

You can use any of the two above operators in your case. Note that $inc can be used with fields with numbers only.

Upvotes: 1

Related Questions