Joe*_* Hu 5 python mongodb mongoengine mongodb-query
我需要在mongoengine中查询包含所有嵌入文档的列表.这是我的架构:
class Variant(EmbeddedDocument):
name = StringField(required=True)
value = StringField(required=True)
class Sku(Document):
variants = ListField(EmbeddedDocumentField(Variant))
Run Code Online (Sandbox Code Playgroud)
我可以用mongo shell做到:
db.sku.find({variants: [{'name': 'xxx', 'value': 'xxx'}]}).pretty()
Run Code Online (Sandbox Code Playgroud)
但是我还没想办法在mongoengine中做到这一点.我需要文档中的列表与我在查询中放入的列表完全相同.有任何想法吗?
Bla*_*ven 10
实际上你也在shell中"错误"地做了这件事.您使用的格式需要一个"很少"实际匹配条件的完全匹配.当然不应该以不同的顺序存储数组的内部键,或者最重要的是数组本身实际存储多个元素.
"shell"的正确形式是:
db.sku.find({ "variants": { "$elemMatch": { "name": "xxx", "value": "xxx" } } })
Run Code Online (Sandbox Code Playgroud)
出于同样的原因,MongoEngine的"正确"形式是:
Sku.objects(variants__match={ "name": "xxx", "value": "xxx" })
Run Code Online (Sandbox Code Playgroud)
__match这里的构造与实例相同,并且实际上$elemMatch在查询中将查询语句作为查询发布到底层MongoDB数据库.
请注意,对于"单个"元素条件,一般的"双下划线"语法就可以了:
Sku.objects(variants__name="xxx")
Run Code Online (Sandbox Code Playgroud)
但是对于数组/列表中的"多个"条件和/或元素,您需要$elemMatch作为MongoDB查询__match.
| 归档时间: |
|
| 查看次数: |
6228 次 |
| 最近记录: |