我有一个包含一些字段(_id、id、名称、状态等)的 Mongo 文档。我在课堂上写了一个典型的文档(就像模型一样):
class mod(Document):
id=fields.IntField()
name = fields.StringField()
status=fields.StringField()
description_summary = fields.StringField()
_id = fields.ObjectIdField()
使用这个模型,我尝试访问它们:
>>> from mongoengine import *
>>> from api.models import *
>>> connect('doc')
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
我试图获取“mod”文档中的所有条目:它成功了!我可以获取所有条目的所有字段(id、name 等...)
>>> mod_ = mod.objects.all()
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
我尝试过滤并返回字段为“status”=“Incomplete”的所有条目:它可以正常工作,就像以前一样。我尝试过滤其他字段:它也可以
>>> mod_ = mod.objects(status="Incomplete")
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
但是当我尝试使用 id 过滤时,我无法得到结果:
>>> mod_ = mod.objects(id=102)
>>> mod_[0].name
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
>>> mod_[0].id
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
所以我尝试了mod.objects.get(id=102)
>>> mod_ = mod.objects.get(id=102)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 271, in get
raise queryset._document.DoesNotExist(msg)
api.models.DoesNotExist: mod matching query does not exist.
Mod 匹配查询不存在,所以它不能识别id字段,但是当我写的时候mod_[0].id
我确实有一个结果,那么有什么问题呢?
编辑:我相信在编写 mod.objects(id=102) 时,字段id被解释为 _id。如何指定,我想通过id而不是_id查询?我的文档已经写好了,所以我不能更改字段的名称。