首页 文章

使用Flask-pymongo扩展通过_id在MongoDB中搜索文档

提问于
浏览
15

我对以下问题感到困惑 .

我正在使用Flask,flask-pymongo扩展,mongodb版本v2.2.0-rc0,pdfile版本4.5

这是我的路线:

@app.route("/check/<id>")
def check(id):
   doc=conn.db.msg.find_one({'_id':id})
   return render_template('base.html',name=doc)

id是msg集合中文档的有效_id,但总是返回None .

我试过了:

  • 使用ObjectId(id)但返回错误类型:ObjectId不可调用

  • 将id作为str(id)返回None

有什么想法吗?

更新:这个完整的URL如何:

http://127.0.0.1:8000/check/5030b628895b800de1a9a792

UPDATE2:

我发现了类似的问题(回答)红宝石 . 不知道我怎么能把它翻译成python,我需要什么样的导入/模块?

How can I retrieve a document by _id?

更新3:我试过:

import bson
@app.route("/check/<id>")
def check(id):
id2="'"+id+"'"
doc=conn.db.msg.find_one({'_id':bson.objectid(id2) })
return render_template('base.html',name=doc)

但是我得到 TypeError: 'module' object is not callable (它也不能用于id)

当我达到1500时,我会建议一个 frustation 标签:-S

UPDATE4:

最后我把它拿起来跑了!

这是我的解决方案:

import bson
@app.route("/check/<id>")
def check(id):
doc=conn.db.msg.find_one({'_id':bson.ObjectId(oid=str(id))})
return render_template('base.html',name=doc)

1 回答

  • 29

    您可能还想尝试使用 bson.objectid 模块中的 ObjectId ,如下所示:

    from bson.objectid import ObjectId
    

    在这种情况下,您不需要提供 oid kwarg . 你会做这样的事情:

    db_conn.msg.find_one({'_id': ObjectId(my_oid)})
    

相关问题