繁体   English   中英

更新pymongo中的集合

[英]Update collection in 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()

for语句后,我的结果为空,因此len为null的问题。 我不知道怎么了 谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM