2016-06-23 83 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()