简体   繁体   中英

How do I compare records in MongoDB for uniqueness based on a field in python using pymongo?

I have a collection with some records and I want to insert only unique values in the collection. I need to compare the new data with old to check if it already exists. If it doesn't exist, then insert it in the collection. I'm using pymongo - create_index(), but I don't know if it's the right way to do it.

First You Have To check if the record exists in the database or not

duplicates = collection.find_one(<query>)

Then if duplicates does not exist then Insert

# check duplicate
if duplicates == None:
    # Insert 
else:
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM