Mongoengine:查询 MapField
Mongoengine: Query a MapField
我有一个要查询的地图字段。类似于:
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))
所以在字段中,配置文件,我像这样存储对象:device_id:DeviceProfile 对象.
我试过:User.objects(profiles__device_id=device_id)
无济于事。我如何查询以便只 return 在配置文件字段中具有特定键的用户对象?基本上,我想根据设备 ID 查询包含某个 DeviceProfile 对象的用户文档。
将此留给遇到此问题的其他人。
为了通过映射字段的键检索 Mongoengine 文档,您使用 exists
运算符。例如,可以构造查询,然后传递给对象方法:
qry = {
'profiles__{}__exists'.format(key): True,
'_cls': 'User'
}
User.object(**qry)
将 exists
运算符视为 "regular" 查询是行不通的,因为任何非空、非零值都将被视为 True
并且匹配将 return MapField 中有内容的任何文档。例如:
Users.object(profiles__exists=key)
将 return 所有具有非空 MapField 的对象。
我有一个要查询的地图字段。类似于:
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))
所以在字段中,配置文件,我像这样存储对象:device_id:DeviceProfile 对象.
我试过:User.objects(profiles__device_id=device_id)
无济于事。我如何查询以便只 return 在配置文件字段中具有特定键的用户对象?基本上,我想根据设备 ID 查询包含某个 DeviceProfile 对象的用户文档。
将此留给遇到此问题的其他人。
为了通过映射字段的键检索 Mongoengine 文档,您使用 exists
运算符。例如,可以构造查询,然后传递给对象方法:
qry = {
'profiles__{}__exists'.format(key): True,
'_cls': 'User'
}
User.object(**qry)
将 exists
运算符视为 "regular" 查询是行不通的,因为任何非空、非零值都将被视为 True
并且匹配将 return MapField 中有内容的任何文档。例如:
Users.object(profiles__exists=key)
将 return 所有具有非空 MapField 的对象。