MongoEngine查询内嵌文档列表
Query Embedded Document List in MongoEngine
我需要在 mongoengine 中查询包含所有嵌入文档的列表。这是我的架构:
class Variant(EmbeddedDocument):
name = StringField(required=True)
value = StringField(required=True)
class Sku(Document):
variants = ListField(EmbeddedDocumentField(Variant))
我可以使用 mongo shell 和:
db.sku.find({variants: [{'name': 'xxx', 'value': 'xxx'}]}).pretty()
但我还没有想出在 mongoengine 中实现它的方法。我需要文档中的列表与我在查询中输入的列表完全相同。有什么想法吗?
实际上您也在 shell "incorrectly" 中这样做了。您使用的格式需要 完全匹配 ,这将 "rarely" 实际匹配条件。数组的内部键当然不会以不同的顺序存储,或最重要的是数组本身实际上存储了不止一个元素。
"shell" 的正确形式是:
db.sku.find({ "variants": { "$elemMatch": { "name": "xxx", "value": "xxx" } } })
同理,MongoEngine的"correct"形式为:
Sku.objects(variants__match={ "name": "xxx", "value": "xxx" })
查询中的__match
construct here is the same thing as, and actually issues an $elemMatch
语句作为对底层MongoDB数据库的查询。
请注意,对于 "single" 元素条件,通用 "double underscore" 语法就可以了:
Sku.objects(variants__name="xxx")
但是对于 "multiple" 条件 and/or 个元素在 array/list 中,你需要 $elemMatch
as a MongoDB query and therefore __match
.
我需要在 mongoengine 中查询包含所有嵌入文档的列表。这是我的架构:
class Variant(EmbeddedDocument):
name = StringField(required=True)
value = StringField(required=True)
class Sku(Document):
variants = ListField(EmbeddedDocumentField(Variant))
我可以使用 mongo shell 和:
db.sku.find({variants: [{'name': 'xxx', 'value': 'xxx'}]}).pretty()
但我还没有想出在 mongoengine 中实现它的方法。我需要文档中的列表与我在查询中输入的列表完全相同。有什么想法吗?
实际上您也在 shell "incorrectly" 中这样做了。您使用的格式需要 完全匹配 ,这将 "rarely" 实际匹配条件。数组的内部键当然不会以不同的顺序存储,或最重要的是数组本身实际上存储了不止一个元素。
"shell" 的正确形式是:
db.sku.find({ "variants": { "$elemMatch": { "name": "xxx", "value": "xxx" } } })
同理,MongoEngine的"correct"形式为:
Sku.objects(variants__match={ "name": "xxx", "value": "xxx" })
查询中的__match
construct here is the same thing as, and actually issues an $elemMatch
语句作为对底层MongoDB数据库的查询。
请注意,对于 "single" 元素条件,通用 "double underscore" 语法就可以了:
Sku.objects(variants__name="xxx")
但是对于 "multiple" 条件 and/or 个元素在 array/list 中,你需要 $elemMatch
as a MongoDB query and therefore __match
.