Search code examples
djangomongodbmongoengineobjectid

Retrieve mongodb documents with int as _id


I imported some wikipedia documents into mongodb with int type "_id" field (they are the pageids for wikipedia page):

> db.wiki_page_id.find()
{ "_id" : 10, "page_title" : "AccessibleComputing" }
{ "_id" : 12, "page_title" : "Anarchism" }

I am using Mongo engine together with Django, and I am having trouble retrieving the documents I imported. When I use the following code:

page_id_doc = WikiPageId.objects(id=10)[0]

it reports this error:

u'10' is not a valid ObjectId, it must be a 12-byte input of type 'str' or a 24-character hex string

When I use the bson.objectid.ObjectId class as this:

page_id_doc = WikiPageId.objects(id=ObjectId(10))[0]

It reports the following error:

id must be an instance of (str, unicode, ObjectId), not

Is there any way to work around this?

Thanks!


Solution

  • With MongoEngine, you can define a field in your document as the "primary key" ( "_id" field by using primary_key in the keyword arguments to the field:

    class MyClass(Document):
        id = IntField(primary_key=True)
    

    But of course you need to make sure that "type" is used everywhere in your collection otherwise the type checking will fail for any "_id" that is not an int().