gpt4 book ai didi

python - MongoEngine:嵌入式文档中的数组位置投影

转载 作者:可可西里 更新时间:2023-11-01 09:55:54 25 4
gpt4 key购买 nike

我正在尝试使用 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'

如有任何帮助,我们将不胜感激!

最佳答案

我不确定 mongoengine 的语法,但我认为您不需要“唯一”位。

$位置指示器通常会从数组中抓取相关值,听上去会涉及到。

关于python - MongoEngine:嵌入式文档中的数组位置投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15683815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com