对于生成的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'>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐