python + pymongo: how to insert a new field on an existing document in mongo from a for loop


Question

I'm using a for loop in python to loop over the result of a query with pymongo. Here is the code:

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...

The question I have is, how can I insert the variable myGeolocCountry into the non existing field geolocCountry on the existing document (b)?

I tried with

b['geolocCountry'] = myGeolocCountry

but it didn't work at all, it does not even produce an error.

Thanks

1
14
3/27/2013 6:04:51 PM

Accepted Answer

You should execute an update query like this:

db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
19
3/28/2013 9:51:45 AM

You have to use the function update() in order to update records in your collection.

With update you can specify a query (just like you have above with collection.find() but also provide a second dict that defines how you want to update the documents found in the query. something like:

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

Check out the API for the rest of the arguments.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon