Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to query MongoDB for _id using string by using Python?

I am using pymongo driver. Supposedly, one can use a string to query the _id field of a document, like this:

thing = db.things.find_one({'_id':'4ea113d6b684853c8e000001'}) 

But it doesn't work. What am I doing wrong?

like image 545
MFB Avatar asked Oct 21 '11 07:10

MFB


People also ask

Can MongoDB _ID be a string?

Yes, you can use a string as your _id.

Which is the correct Python driver maintained by the MongoDB?

Although there are other drivers written by the community, PyMongo is the official Python driver for MongoDB.


1 Answers

It should be :

from pymongo.objectid import ObjectId    thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001') }) 

EDIT: The current import is: from bson.objectid import ObjectId

like image 145
DhruvPathak Avatar answered Oct 19 '22 18:10

DhruvPathak