2017-05-04 78 views
0

我必須在MongoDB中插入記錄。我用了一個簡單的邏輯,但沒有奏效。請幫我解決這個問題。Mongo DB,Python:每插入10000條記錄都會插入。

from pymongo import MongoClient 
import json 
import sys 
import os 
client = MongoClient('localhost', 9000) 
db1 = client['Com_Crawl'] 
collection1 = db1['All'] 
posts1 = collection1.posts 
ll=[] 
f=file(sys.argv[1],'r') 
for i in f: 
    j=json.loads(i) 
    ll.append(j) 
#print ll 
print len(ll) 
count = 0 
for l in ll: 
    count = count+1 
    if count <= 10000: 
     print count,l 
     print posts1.update({'vtid':l},{'$set': {'processed': 0}},upsert = True,multi = True) 
print "**** Success ***" 

該文件包含1000萬條記錄。上面的代碼插入了一個新列,並將它的值更新爲「0」以記錄10000條記錄。但是如何能夠在每批執行10000個批處理中記錄其餘的記錄。

+0

不確定批處理部分,但此循環僅在'count <= 10000'時掛起,且計數從不重置。所以一旦你打10000個記錄,upsert不會再發生。 – ktbiz

+0

是的..但是我怎樣才能重置下一組值的計數。 – NiviSRa

+0

您可能只想以10000爲單位遞增,並在每個步驟插入一片「ll」。使用'range'而不是遍​​歷每個元素。 – ktbiz

回答

0

Mongodb有批量更新操作,它將批量更新數據庫。你可以添加任何字典,並可以一次更新,但它會在內部更新1000到1000批次refer this以獲得有關有序和無序批量操作的想法,並獲得有關批量更新refer this的想法,以瞭解批量操作如何工作。所以,如果你遵循批量更新它wiil是

from pymongo import MongoClient 
client = MongoClient('localhost', 9000) 
db1 = client['Com_Crawl'] 
collection1 = db1['All'] 
posts1 = collection1.posts 
bulk = collection1.posts.initialize_unordered_bulk_op() 
ll=[] 
f=file(sys.argv[1],'r') 
for i in f: 
    j=json.loads(i) 
    ll.append(j) 
#print ll 
print len(ll) 
count = 0 
for index,l in enumerate(ll): 
    bulk.find({'vtid':l}).update({'$set': {'processed': 0}},upsert = True,multi = True) 
    if (index+1)%10000 == 0: 
     bulk.execute() #this updates the records and prints the status. 
     bulk = collection1.posts.initialize_unordered_bulk_op() #reinitialise for next set of operations. 
bulk.execute() #this updates the remaining last records. 

爲指向的喬d你也可以跳過散裝記錄和更新。

+0

感謝瑪尼。但是我遇到了AttributeError:'BulkOperationBuilder'對象沒有屬性'update'。 – NiviSRa

+0

哦,好的。現在讓我試試。我有個疑問;現在update()需要upsert選項嗎?因爲當我在查詢中使用find時,bulk.find({'vtid':l}).update({'$ set':{'processed':0}},upsert = True,multi = True) TypeError :update()得到了一個意想不到的關鍵字參數'upset'' – NiviSRa

+0

當你設置'upsert = True'時,如果找不到匹配項,它將創建新記錄。如果'upsert'設置爲'false',如果沒有找到匹配,它將不會執行任何操作。還請注意,在發佈的評論中,我看到它在錯誤中被稱爲「不安」。請檢查一下。 – Mani

1

你可以這樣做,而不是。

for l in ll: 
    for post in posts1.find({}).skip(count*10000).limit(10000): 
     print post.update({'vtid':l},{'$set': {'processed': 0}},upsert = True,multi = True) 
    count += 1 
print "**** Success ***" 

skip()究竟是幹什麼的,你會覺得,它跳過,在查詢集的條目,然後limit()限制導致爲10000。所以基本上你使用count得到的條目從0開始,10000, 20000等,並且在該起點之後僅限制10000次。

+0

謝謝Joe D.我現在就試試。 – NiviSRa

+0

TypeError:'集合'對象不可調用。如果您打算在「集合」對象上調用「跳過」方法,則它將失敗,因爲不存在此類方法。我遇到了這個錯誤。 @Joe D – NiviSRa

+0

道歉,我沒有看到它是一個集合,我會更新它。 @NiviSra –