在pymongo更新集合

时间:2016-06-23 09:42:49

标签: python mongodb mongodb-query aggregation-framework

我想检查插入到我的收藏中的文件数量。

这是我在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()

在for语句之后,我的结果为空,因此len为null。我不知道什么是错的。 谢谢

1 个答案:

答案 0 :(得分:1)

collection.aggregate()方法返回CommandCursor,它有点像Python生成器,只能迭代一次。因此,当您调用list(result)时,您将无法重新迭代光标。

您可以做的是在for循环内计算result中的文档数量,而不事先创建array

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()