3
votes

I am trying to reproduce the following query in python using MongoEngine without much success.

Original source for data and query: http://docs.mongodb.org/manual/reference/projection/positional/#prj._S_

The query basically returns the first element matched in the embedded document and not the whole embedded document itself.

My code:

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

When I do this, I get an error:

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'

Any help would be much appreciated!

2

2 Answers

0
votes

I'm not sure of mongoengine's syntax, but I think you don't need the "only" bit.

The $ positional indicator usually grabs relevant values from the array, and it sounds like it will be involved.

0
votes

The positional operator is for updating the first element inside an array that matches your query.

The query language is about finding documents and currently you cannot filter an array inside a document. You can slice and return a subset of the array, but not only return a matched subset.

So in this case you'd have to filter the grades in python and as part of the loop.

An alternative strategy might be to use the aggregation framework to $unwind the array and $match and then rebuild the grades array - but that is not built into mongoengine at this time.