zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    <C#>关于string.Empty & "" & null 的讨论
    c# checked unchecked 关键字 try
    sql2005数据库加锁后解锁
    c#对字符串转义符进行解码
    继承本质论
    javascript中parseInt和Number函数的用法区别
    BIRT 使用说明书
    最后一周
    修改字段
    SQLserver中join
  • 原文地址:https://www.cnblogs.com/HuZihu/p/11167124.html
Copyright © 2011-2022 走看看