Search code examples
pythonpymongo

Add a field in doc if it does not exist else update


I am using the below code to update job_start_time in a doc:

myclient = pymongo.MongoClient("mongodb://10.64.127.94:27017/")
mydb = myclient["UPTeam"]
mycol = mydb["perf_sdwan_queue"]
myquery = {"$and":[ {"job_job_id": current_job_id}, {"job_queue_name": "CURIE_BLR"}]}
my_jobs = mycol.find(myquery)
newvalues = { "$set": { "job_start_time":datetime.datetime.utcnow()} }
mycol.update_one(myquery, newvalues)

This works fine if the field exists. I want to have a code where it either updates the field if it exists else to create a new field.


Solution

  • I don't think you need to change anything. $set will create the field if it doesn't exist, or update it if it does.

    https://www.mongodb.com/docs/manual/reference/operator/update/set/#behavior

    If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint.