Search code examples
pythonmongoengine

Retrieving a document where one of its reference fields fulfill a condition


I am trying to retrieve the id from the child document based on a condition of one of its fields . Here are the document schemas.

class father(DynamicDocument):
    name = StringField

class child(DynamicDocument):
    name = StringField
    parent = ReferenceField('father')

How can I get the id of the child where its father's name is 'Anakin'?

I am trying with this query:

Child.objects.filter(parent__name=Father.objects(name='Anakin').first().id).first().id

But it results to:

mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: parent__name

Solution

  • There is no easy way to do this in 1 query as MongoDB has no join.

    The recommended way to do this with MongoEngine, is by using 2 queries:

    anakin = Father.objects(name='Anakin').first()
    anakin_childs = Child.objects.filter(parent=anakin) #.first() if you are only interested in first match
    

    The CachedReferenceField may also be of interest to you, it caches (i.e duplicate) some attributes in the parent collection allowing you to do such "join". But it comes with decreased performance due to the overhead of keeping the cached attribute in sync with the original document.