我試圖在沒有太多成功的情況下使用MongoEngine在python中重現以下查詢。MongoEngine:嵌入式文檔中的陣列位置投影
用於數據和查詢原始來源: 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'
任何幫助,將不勝感激!
感謝您的回覆。但是,mongodb [doc](http://docs.mongodb.org/manual/reference/projection/positional/)指出位置操作符用於選擇數據和更新數據。我最終直接在MongoDB中執行這個查詢。 – ducky