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

转载于:https://www.cnblogs.com/HuZihu/p/11167124.html

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值