2016-06-23 11 views
0

Ich möchte die Nummer des Dokuments in meine Sammlung eingefügt überprüfen.Update-Sammlung in Pymongo

Hier ist mein Code in 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() 

das Problem, dass nach der für Anweisung, mein Ergebnis leer ist, und so die len ist null. Ich weiss nicht, was falsch ist. Danke

Antwort

1

Die collection.aggregate() Methode gibt eine CommandCursor zurück, die wie ein Python-Generator ist, der nur einmal iterable ist. Wenn Sie also list(result) aufrufen, können Sie den Cursor nicht erneut durchlaufen.

Was können Sie stattdessen tun, ist die Anzahl der Dokumente in result innerhalb der for-Schleife zu zählen, ohne die array vor der Hand zu schaffen:

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