Pymongo Check if record exists, if not, then insert, on the basis of column which is the unique key

160 views Asked by At

I am using python to update the data in my MongoDB database. I want to insert the data frame rows only if it does not already exist in the Database. I want to check the existence of the record using only one column- variant_id (unique key). The variant_id which are already present in the database, should not get modified. Only the new variant_id should be getting appended.

Original Database Table-

enter image description here

New Dataframe to be inserted-

enter image description here

Database Table After Insertion-

enter image description here

1

There are 1 answers

0
ter On

try this did you means this?

db = client['testdata']
testCollection = db['collectionName']

df =  pd.DataFrame(list(testCollection.find({})))
df.info()


def insert_data(df):
    meta = df.to_dict('records')
    testCollection.insert_many(meta)

if df.empty:
    insert_data(ji10001)