How to get object id in pymongo?

I am trying to get the id of the document I was contacting. My database is mongodb and I use pymongo in the bulb Here is my code

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

I tried this too

 doc_id=docQuery[0]["_id"]

None of them work!

+4
source share
1 answer

Although your second approach should work, it docQueryis an object of type Cursor. The best way is to iterate over it, for example:

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

Or, if there is only one object, use find_oneas:

itm = db.doctors.find_one({"email":doc_mail})
print itm.get('_id')
+7
source

All Articles