简体   繁体   English

如何使用pymongo根据python中的字段比较MongoDB中的记录的唯一性?

[英]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. 我正在使用pymongo-create_index(),但我不知道这是否是正确的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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