35

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?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
MFB
  • 19,017
  • 27
  • 72
  • 118

5 Answers5

62

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

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
39

PyMongo has changed its structure. ObjectID is no longer imported from pymongo, but from bson. It should now be:

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

As a reminder, per pypi/pymongo, do not install the “bson” package. PyMongo comes with its own bson package; doing “pip install bson” installs a third-party package that is incompatible with PyMongo.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Sean
  • 2,315
  • 20
  • 25
  • see http://stackoverflow.com/questions/10401499/mongokit-importerror-no-module-named-objectid-error – Sean Jun 26 '13 at 15:33
3

To print it:

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

if you don't want to print, store in other variable

Jigyasu Tailor
  • 153
  • 2
  • 8
0

PyMongo documentation does not seem to be in sync with the current version. ObjectIds are now under bson.objectid namespace. If I remember right, they have been that way since version 2.3. Use from bson.objectid import ObjectId.

0

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

lobster1234
  • 7,679
  • 26
  • 30
  • thanks lobster1234 your answer is also correct, but it was the import I was missing, cheers – MFB Oct 22 '11 at 00:37