2013-03-27 14 views
12

Pymongo'yu içeren bir sorgunun sonucu üzerinde döngü yapmak için python için bir for döngüsü kullanıyorum. İşte kod: Ben bir soru, nasıl varolan belgenin (b) olmayan varolan alanda geolocCountry içine değişkeni myGeolocCountry ekleyebilirsiniz edilir python + pymongo: for döngüsünden mongo'da varolan bir belgeye yeni bir alan ekleme

from pymongo import MongoClient 
connection = MongoClient() 
db = connection.Test 

myDocs = db.Docs.find({ "geolocCountry" : { "$exists" : False } }) 

for b in myDrives: 
    my_lat = b['TheGpsLog'][0]['latitude'] 
    my_long = b['TheGpsLog'][0]['longitude'] 

    myGeolocCountry = DoReverseGeocode(lat_start,long_start) 
    # Here I perform a reverse geocoding, it does not matter for this example. 
    # The important thing is: it returns a string, like 'US', 'UK', etc... 

?

Ben

b['geolocCountry'] = myGeolocCountry 

ile çalıştı ama hiç, hatta bir hata üretmez çalışmadı.

Teşekkür

cevap

12

Bir güncelleştirme sorgusu böyle yürütmek olmalıdır:

db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}}) 
+0

i soo bu deneyeceğim n, teşekkürler – otmezger

+0

Çalıştı, çözümün küçük bir hata, tho. '' myGeolocCountry' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ' – otmezger

2

Sen koleksiyonunda kayıtlarını güncellemek için işlevini update() kullanmak zorunda. güncellemeyle

Eğer collection.find() ile yukarıda sahip ama aynı zamanda sorguda bulunan belgeleri güncelleştirmek istiyorum nasıl gibi şey tanımlayan ikinci dicti sağlamak gibi sen (bir sorgu belirtebilirsiniz.

db.Docs.update({"geolocCountry":{"$exists":False}}, {"$set": "geolocCountry": myGeolocCountry}) 

. Eğer güncellemeden sonra toplama kaydetmeniz gerekir. argümanlar geri kalanı için

0

API göz atın

for b in myDrives: 
    my_lat = b['TheGpsLog'][0]['latitude'] 
    my_long = b['TheGpsLog'][0]['longitude'] 

    myGeolocCountry = DoReverseGeocode(lat_start,long_start) 

    b['geolocCountry'] = myGeolocCountry 
    **db.Docs.save(b)** 
İlgili konular