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
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method. The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert.
So, Adding a new field to an array is possible by using the update operation. $push operator is used to insert the field inside the array and if we want to add multiple fields, use $each inside $push.
You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
You should execute an update query like this:
db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
For pymongo > 3
db.Doc.update_one({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
In case of multiple updates:
db.Doc.update_many({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})
For pymongo < 3
above/previous answers are correct
db.Doc.update({"_id": b["_id"]}, {"$set": {"geolocCountry": myGeolocCountry}})
In case of multiple updates:
db.Doc.update({"geolocCountry": {"$exists": False}}, {"$set": {"geolocCountry": myGeolocCountry}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With