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

如下摘自pymongo文档:html

update_one(filterupdateupsert=False)python

update_many(filterupdateupsert=False)mongodb

  • 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便可,此时表示若是没有找到匹配的文件,那么执行插入操做。数据库

 

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

{'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)。app

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函数

相关文章
相关标签/搜索