Search code examples
pythonmongodbpython-3.xmongoengineodm

Mongoengine: Query a MapField


I have a map field that I want to query by. Something like:

class User(mongoengine.Document):
    email = mongoengine.EmailField(required=False, unique=False)
    username = mongoengine.StringField(max_length=30, min_length=6, required=True, unique=True)
    password = mongoengine.StringField(max_length=500, min_length=6, required=True)
    profiles = mongoengine.MapField(mongoengine.EmbeddedDocumentField(DeviceProfile))

So in the field, profiles, I store the objects like so: device_id: DeviceProfile object.

I tried: User.objects(profiles__device_id=device_id) to no avail. How do I query so that I only return User objects that have a specific key in the profiles field? Basically, I want to query for User documents that contain a certain DeviceProfile object based on its device ID.


Solution

  • Leaving this here for anyone else that runs into this problem.

    In order to retrieve the Mongoengine document by the key of the map field, you use the exists operator. For example, the query can be constructed and then passed to the object method:

    qry = {
        'profiles__{}__exists'.format(key): True,
        '_cls': 'User'
    }
    
    User.object(**qry)
    

    Treating the exists operator like a "regular" query doesn't work since any non-null, non-zero value will be treated as True and the match will return any Documents where there is something in the MapField. For example:

    Users.object(profiles__exists=key)
    

    will return all objects that has a non-empty MapField.