Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert hex string to ObjectId in Python [duplicate]

I a list of ObjectId's that I'm iterating over to the find values in a dict where the keys are ObjectId's.

email_count = 0
# user_id_list is a list of ObjectId's
for user_id in user_id_list:
    # UuserIdemailCountD is a dict where they keys are objectIds
    email_count +=  UuserIdemailCountD[user_id]

I keep getting the following error:

email_count +=  UuserIdemailCountD[user_id]
KeyError: ObjectId('54a9c84ebf2e4e5b258b5412')

When i iterate over user_id_list and just print the ids, I get a plain string like this 54a9c84ebf2e4e5b258b5412.

Is the answer to convert the string to ObjectId's? If so, how?

like image 507
DBWeinstein Avatar asked May 22 '15 23:05

DBWeinstein


1 Answers

Import ObjectId:

from bson import ObjectId

From ObjectId to string:

oid = ObjectId()
oid_str = str(oid)
# oid_str is now '555fc7956cda204928c9dbab'

From string to ObjectId:

oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')
like image 151
Messa Avatar answered Oct 22 '22 23:10

Messa