2016-12-15 81 views
0

我寫這個腳本插入一個doc文檔轉成MongoDB中,如果不重複有關MongoDB插入,如果不重複

import tldextract 
from pymongo import MongoClient 

client = MongoClient() 
db = client.my_domains 
collection = db.domain 

with open('inputcut.csv', 'r') as f: 
    for line in f: 
    ext = tldextract.extract(line) 
    domain = {"domain":ext.registered_domain} 
    collection.update(domain,{'upsert':True}) 

當我運行該腳本,沒有域插入到數據庫中。 我想插入一個域,如果它尚未出現在mongodb中。 如果該域名已經存在,我們不會插入它,我們會去下一個域名...

在此先感謝您的幫助。

+0

您是否打算在集合中的「域」更新文檔? – styvane

+0

http://stackoverflow.com/questions/36083247/how-to-continue-insertion-after-duplicate-key-error-using-pymongo – styvane

回答

0

collection.update需要3個參數 - 查詢,更新和選項。由於upsert應該在選項中,請按以下方式重寫呼叫:

collection.update(domain, {$set: domain}, {'upsert':True})