2016-06-23 80 views
0

我想檢查插入到我的集合中的文檔數量。pymongo中的更新集合

這是我在Python代碼:

from pymongo import MongoClient 
connection = MongoClient() 
db = connection['mydatabase'] 
collection1 = db.mycollection 
collection2=db.mycollection1 
pipe = [{......}] 
result = collection1.aggregate(pipe, allowDiskUse=True) 

array = list(result) 
length = len(array) 

for res in result: 
    id = res['_id'] 
    collection2.update({..}, upsert=True) 
count = collection2.find().count() 
print ("There are %d documents in users collection" %count) 

if length == count: 
    print("insertion ok") 
else: 
    print("echec") 

connection.close() 

,對於語句後,我的結果是空的,所以len爲空的問題。我不知道什麼是錯的。 謝謝

回答

1

collection.aggregate()方法返回一個CommandCursor,它有點像Python生成器,只能迭代一次。因此,當你調用list(result)時,你將不能重新遍歷遊標。

你可以做的反而是沒有事先創建array數內的for循環result的文件數量:

from pymongo import MongoClient 
connection = MongoClient() 
db = connection['mydatabase'] 
collection1 = db.mycollection 
collection2 = db.mycollection1 
pipe = [{......}] 
result = collection1.aggregate(pipe, allowDiskUse=True) 

length = 0 
for res in result: 
    id = res['_id'] 
    collection2.update({..}, upsert=True) 
    length += 1 

count = collection2.count() 
print ("There are %d documents in users collection" %count) 

if length == count: 
    print("insertion ok") 
else: 
    print("echec") 

connection.close()