使用int作为_id检索mongodb文档

时间:2021-12-14 04:14:27

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

我将一些*文档导入mongodb,其中int类型为“_id”字段(它们是*页面的pageid):

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

I am using Mongoengine together with Django, and I am having trouble retieving the documents I imported. When I use the following code:

我和Django一起使用Mongoengine,我无法收到我导入的文件。当我使用以下代码时:

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:

当我使用bson.objectid.ObjectId类时:

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

It reports the following error:

它报告以下错误:

id must be an instance of (str, unicode, ObjectId), not <type 'int'>

Is there any way to work around this?

有什么方法可以解决这个问题吗?

Thanks!

谢谢!

1 个解决方案

#1


1  

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:

使用MongoEngine,您可以在文档中将字段定义为“主键”(“_id”字段,方法是在字段的关键字参数中使用primary_key:

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().

但是当然你需要确保在你的集合中的任何地方都使用“type”,否则对于任何不是int()的“_id”,类型检查都会失败。

#1


1  

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:

使用MongoEngine,您可以在文档中将字段定义为“主键”(“_id”字段,方法是在字段的关键字参数中使用primary_key:

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().

但是当然你需要确保在你的集合中的任何地方都使用“type”,否则对于任何不是int()的“_id”,类型检查都会失败。