Search document in MongoDB by _id using Flask-pymongo extension

12,413

You might also want to try using ObjectId from the bson.objectid module, like so:

from bson.objectid import ObjectId

In that case, you won't need to provide the oid kwarg. You'll just do something like this:

db_conn.msg.find_one({'_id': ObjectId(my_oid)})
Share:
12,413
Altons
Author by

Altons

Statistician, data pervert, always learning useful & useless stuff. Great fan of: FC Barcelona New York Yankees Liverpool FC Great believer of life is what happens whilst we work!

Updated on June 07, 2022

Comments

  • Altons
    Altons almost 2 years

    I am baffled with the following problem.

    I am using Flask, flask-pymongo extension, mongodb version v2.2.0-rc0, pdfile version 4.5

    This is my route:

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

    the id is a valid _id from a document in the msg collection, but ALWAYS return None.

    I have tried:

    • pasing the ObjectId(id) but returns errortype: ObjectId not callable
    • pasing the id as str(id) returns None

    Any thoughts?

    UPDATE: this how the full url looks like:

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

    UPDATE2:

    I found a similar question with (answer) for ruby. Not sure how I can translate it to python, what sort imports/modules do I need?

    How can I retrieve a document by _id?

    UPDATE3: I tried:

    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)
    

    but I get TypeError: 'module' object is not callable (it doesnt work with id either)

    when I reached 1500 I will suggest a frustation tag :-S

    UPDATE4:

    Finally I got it up & running!

    here it is my solution:

    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)
    
  • A. Jesse Jiryu Davis
    A. Jesse Jiryu Davis over 11 years
    By the way, we're updating the PyMongo docs for the next release to warn people about this pitfall: github.com/mongodb/mongo-python-driver/commit/… Hope that helps.
  • Gevious
    Gevious about 11 years
    the import has moved to from bson.objectid import Objectid
  • Rohan Devaki
    Rohan Devaki about 3 years
    there is an error from bson.py3compat import abc, string_type, PY3, text_type ImportError: cannot import name 'abc' from 'bson.py3compat'
  • Rohan Devaki
    Rohan Devaki about 3 years
    dont install bson at atll, currently there is this above error
  • Rohan Devaki
    Rohan Devaki about 3 years
    do we have any other option to get the objectid function?