我正在使用带有 pymongo 的烧瓶,并且有一个案例,我的对象 ID 被转换为字符串。如何将其改回对象 ID 以便我可以使用 if 进行查询?
From : 59d7ef576cab3d6118805a20
type is <class 'str'>
To: ObjectId("59d7ef576cab3d6118805a20")
type is <class 'bson.objectid.ObjectId'>
Run Code Online (Sandbox Code Playgroud) 我最近开始使用 Pymongo,现在我想找到删除 Response 中 $oid 的最佳方法
当我使用时find
:
result = db.nodes.find_one({ "name": "Archer" }
Run Code Online (Sandbox Code Playgroud)
并得到响应:
json.loads(dumps(result))
Run Code Online (Sandbox Code Playgroud)
结果将是:
{
"_id": {
"$oid": "5e7511c45cb29ef48b8cfcff"
},
"about": "A jazz pianist falls for an aspiring actress in Los Angeles."
}
Run Code Online (Sandbox Code Playgroud)
我的预期:
{
"_id": "5e7511c45cb29ef48b8cfcff",
"about": "A jazz pianist falls for an aspiring actress in Los Angeles."
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我们可以使用:
resp = json.loads(dumps(result))
resp['id'] = resp['id']['$oid']
Run Code Online (Sandbox Code Playgroud)
但我认为这不是最好的方法。希望大家有更好的解决方案。