I'm getting data from Mongo with Python. I move all the documents from the cursor into an array. Then I process the documents and try to add some new properties to the object / dictionary, but it says KeyError. I've seen this behavior in Nodejs when trying to modify objects returned by mongo and the solution there is query.lean().exec() to get plain objects. Does pymongo have an equivalent?
Asked
Active
Viewed 595 times
0
-
You used `nontree` style, so `mongo > dump > change >update` because imposible `mongo-hash to mongo-hash(mongo-hash)` ! You got big problem if your update contained another `query filter`. Check this: http://stackoverflow.com/questions/18363472/mongoose-lean-query-virtuals-not-showing – dsgdfg Jul 16 '16 at 19:53
-
I don't understand. I made the query and got data. Now I'm trying to manipulate it within my program. I haven't updated the db itself (yet). – user137717 Jul 16 '16 at 19:56
-
work with `jsonID`, so define any `_id` ? https://docs.mongodb.com/manual/reference/method/db.collection.update/ @user137717 – dsgdfg Jul 16 '16 at 20:07
1 Answers
0
KeyError's are not raised when setting new keys on a dict. Meaning you are doing something wrong.
See when a KeyError is raised: https://stackoverflow.com/a/10116540/4273834
Just to recap: A KeyError is not raised if you try to SET a key but rather if you try to GET a value for a key which does not exist.
Here is a code snippet which works:
cursor = col.find({})
my_list = list(cursor)
my_list[0]['added_field'] = 'whatever'
Just a side note: list(cursor) is not the way how to process data in python. The recommended way is to loop over the cursor directly (unless there is some specific reason to have a list...):
for doc in cursor:
doc['new_key'] = 'test'
do_whatever_you_want_with_the_doc(doc)

Community
- 1
- 1

squanto773
- 494
- 5
- 12