python - Mongoengine:查询 MapField

标签 python mongodb python-3.x mongoengine odm

我有一个要查询的 map 字段。像这样的东西:

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 对象的用户文档。

最佳答案

将此留给遇到此问题的任何其他人。

为了通过映射字段​​的键检索 Mongoengine 文档,您使用 exists 运算符。例如,可以构造查询,然后将其传递给对象方法:

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

User.object(**qry)

exists 运算符视为“常规”查询是行不通的,因为任何非空、非零值都将被视为 True 并且匹配将返回 MapField 中有内容的任何文档。例如:

Users.object(profiles__exists=key)

将返回所有具有非空 MapField 的对象。

关于python - Mongoengine:查询 MapField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43416883/

相关文章:

python - 将给定字母表的字符串转换为整数

linux - 尝试启动 mongodb 时出错

java - Play-Morphia with Play 1.4

python - SQLalchemy:更改未提交到数据库

python scipy lesssq 适合复数

mongodb - 'MongoError : setName from ismaster does not match provided connection setName' when trying to connect to a MongoDB cluster using mongoose

python-3.x - 从数据框中的列表中过滤列的最佳方法

python - 替换多个(特殊)字符 - 最有效的方法?

Python 3 通过发送 Ctrl C 停止子进程

python - 如何满足这种依赖要求呢?