MongoDB---如何避免插入重复数据(pymongo)

以下摘自pymongo文档:

update_one(filterupdateupsert=False)

update_many(filterupdateupsert=False)

  • filter: A query that matches the document to update.
  • update: The modifications to apply.
  • upsert (optional): If True, perform an insert if no documents match the filter.

 

这两个是pymongo库的数据更新函数,其中upsert默认为False。如果我们想要把数据加入数据库,同时想要避免插入重复的数据,那么只要把upsert改为True即可,此时表示如果没有找到匹配的文件,那么执行插入操作。

 

例如,我想把下面这条数据保存至数据库,但是如果这条数据已经在数据库存在了,那么不进行任何操作。

{'index': '1', 'movie_name': '霸王别姬', 'pic': 'https://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c', 'release': '上映时间:1993-01-01', 'score': '9.5'}

 

那么应该把这条数据作为查询语句,然后执行collection.update_one(query,{'$set':query},upsert=True)。

query={'_id': ObjectId('5d23fc92c2a80d7e578a2ae2'), 'index': '1', 'movie_name': '霸王别姬', 'pic': 'https://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c', 'release': '上映时间:1993-01-01', 'score': '9.5'}
collection.update_one(query,{'$set':query},upsert=True)

 

参考:http://api.mongodb.com/python/current/api/pymongo/collection.html

posted @ 2019-07-11 10:57  HuZihu  阅读(3004)  评论(0编辑  收藏  举报