对于生成的id,直接用str()
即可转为字符串,而对于字符串,使用bson.objectid.ObjectId
将字符串转为ObjectId
类型
示例代码
from bson.objectid import ObjectId
str_id = "62ef8ac55e820c5d091e7380"
object_id = ObjectId(str_id) # 字符串转ObjectID
print(object_id, type(object_id))
string_id = str(object_id) # ObjectID转字符串
print(string_id, type(string_id))
得到结果:
62ef8ac55e820c5d091e7380 <class 'bson.objectid.ObjectId'>
62ef8ac55e820c5d091e7380 <class 'str'>