[英]Update collection in pymongo
I would like to check the number of document inserted into my collection. 我想检查插入收藏夹中的文档数量。
Here is my code in Python: 这是我在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()
the problem that after for statement, my result is empty and so the len is null. for语句后,我的结果为空,因此len为null的问题。 I don't know what's wrong. 我不知道怎么了 Thank you 谢谢
The collection.aggregate()
method returns a CommandCursor
, which is kind of like a Python generator that is iterable for only once. collection.aggregate()
方法返回一个CommandCursor
,它类似于Python生成器,只能迭代一次。 Therefore when you call list(result)
you will not be able to re-iterate over the cursor. 因此,当您调用list(result)
您将无法在光标上再次迭代。
What you can do instead is to count the number of documents in result
within the for loop without creating the array
before hand: 相反,您可以做的是在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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.