我有一个要查询的地图字段。类似于:
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))因此,在字段profiles中,我存储的对象如下: device_id: DeviceProfile对象。
我试过:User.objects(profiles__device_id=device_id)没有用。如何进行查询,以便只返回配置文件字段中具有特定键的用户对象?基本上,我想根据用户的设备ID查询包含特定DeviceProfile对象的用户文档。
发布于 2017-04-15 16:27:42
把这个留给其他遇到这个问题的人。
为了通过map字段的键检索Mongoengine文档,可以使用exists操作符。例如,可以构造查询,然后将其传递给object方法:
qry = {
'profiles__{}__exists'.format(key): True,
'_cls': 'User'
}
User.object(**qry)将exists操作符视为“常规”查询不起作用,因为任何非空、非零值都将被视为True,并且匹配将返回MapField中有内容的任何文档。例如:
Users.object(profiles__exists=key)将返回所有具有非空MapField的对象。
https://stackoverflow.com/questions/43416883
复制相似问题