簡體   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