Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search document in MongoDB by _id using Flask-pymongo extension

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)
like image 739
Altons Avatar asked Aug 29 '12 09:08

Altons


Video Answer


1 Answers

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)})
like image 88
aezell Avatar answered Sep 22 '22 06:09

aezell