how to convert hex string to ObjectId in Python [d

2019-02-25 02:47发布

This question already has an answer here:

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?

1条回答
三岁会撩人
2楼-- · 2019-02-25 03:41

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')
查看更多
登录 后发表回答