Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the id from an ObjectID, using Python?

I am trying to get the id from the document which I have in MongoDB, using PyMongo.

Here is my code:

docQuery = db.doctors.find({"email":doc_mail})
doc_id = docQuery[0]["_id"]["$oid"]

I have tried this too:

 doc_id = docQuery[0]["_id"]

Neither of them works!

like image 863
user3425344 Avatar asked Jun 26 '15 16:06

user3425344


2 Answers

Though your second approach should work, docQuery is a Cursor type object. Best way is to iterate over it like:

for itm in db.doctors.find({"email":doc_mail}):
   print itm.get('_id')

Or if there is only one object, then use find_one like:

itm = db.doctors.find_one({"email":doc_mail})
print itm.get('_id')
like image 173
salmanwahed Avatar answered Sep 18 '22 15:09

salmanwahed


In pymongo you can use [''] this notation to access the specific property.
Example -

cursor = collection.find({})
for document in cursor:
        print document['_id']
like image 31
Adarsh Srivastava Avatar answered Sep 16 '22 15:09

Adarsh Srivastava