You are viewing a single comment's thread from:

RE: PyMongo开发指南

in #starnote • 4 days ago

在 Web 应用程序中,一个常见的任务是从请求 URL 中获取 ObjectId 并查找匹配的文档。在这种情况下,在将 ObjectId 传递给 find_one 之前,必须先将其从字符串转换为对象。按 _id 查询要先转 ObjectId。

from bson import ObjectId

doc = collection.find_one({"_id": ObjectId("690123456789abcdef012345")})
# 错误写法:find_one({"_id": "690123456789abcdef012345"})  # 字符串匹配不到 ObjectId

# The web framework gets post_id from the URL and passes it as a string
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})