我正在尝试使用 MongoEngine 在 python 中重现以下查询,但没有取得多大成功。
数据和查询的原始来源:http: //docs.mongodb.org/manual/reference/projection/positional/#prj._S_
该查询基本上返回嵌入文档中匹配的第一个元素,而不是整个嵌入文档本身。
我的代码:
from mongoengine import *
connect('test')
class Student(Document):
semester = IntField()
grades = ListField(EmbeddedDocumentField('Grade'))
class Grade(EmbeddedDocument):
value = FloatField()
def __str__(self):
return "%s" % self.value
student_1 = Student(semester=1, grades=[Grade(value=70), Grade(value=87), Grade(value=90)]).save()
student_2 = Student(semester=1, grades=[Grade(value=90), Grade(value=88), Grade(value=92)]).save()
result = Student.objects(semester=1, grades__value__gte=85).only("grades.$")
for r in result:
print r.grades
当我这样做时,我得到一个错误:
Traceback (most recent call last):
File "test_me_so.py", line 21, in <module>
result = Student.objects(semester=1, grades__value__gte=85).only("grades.$")
File "/.../lib/python2.7/site-packages/mongoengine/queryset.py", line 1225, in only
return self.fields(**fields)
File "/.../lib/python2.7/site-packages/mongoengine/queryset.py", line 1271, in fields
fields = self._fields_to_dbfields(fields)
File "/.../lib/python2.7/site-packages/mongoengine/queryset.py", line 1289, in _fields_to_dbfields
field = ".".join(f.db_field for f in QuerySet._lookup_field(self._document, field.split('.')))
File "/.../lib/python2.7/site-packages/mongoengine/queryset.py", line 1289, in <genexpr>
field = ".".join(f.db_field for f in QuerySet._lookup_field(self._document, field.split('.')))
AttributeError: 'str' object has no attribute 'db_field'
任何帮助将非常感激!