Search code examples
mongodbinsertconditional-statementspymongomongodb-update

Update and insert together in mongodb using pymongo?


I have a list of dictionaries as follows:

data=[{
      "uni_id": '101',
      "name":"abc",
      "age": 10,
    },
    { 
     "uni_id": '102',
      "name":"def",
      "age": 12,

     }]

I want to use this dictionary to update my database only if the "uni_id" exists in the database, if it doesn't exist in my database then I want to insert that particular "uni_id" and also its corresponding "name" and "age":

My update statement is as follows, however I would also like to use insert with it to satisfy the above mentioned conditions. How to write the insert statement? Or is there a way to write some if-else statements to do update and insert?

db.students.update_one(
    {"uni_id":data[0]['uni_id']},
    {
    "$set":
   {
    "name":"abc_1",
   }})

Solution

  • Set upsert to true... It creates a new document if the updated document is not existed in the collection

    db.students.update_one(
      { "uni_id": data[0]['uni_id']},
      { "$set": { "name":"abc_1" }},
      True
    )