以下摘自pymongo文檔:
update_one
(filter, update, upsert=False)
update_many
(filter, update, upsert=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