python - 匹配 EmbeddedDocumentList 中的 EmbeddedDocument

标签 python django mongodb mongoengine

所以我在 mongo 中有这个测试数据,Cart 模型:

{
"_id" : ObjectId("55eb513c516ddc8fa6e68886"),
    "user" : ObjectId("55e3f236516ddc78296968be"),
    "items" : [
        {
            "item" : ObjectId("55eb10b8516ddc7508dba7c2"),
            "quantity" : 1,
            "added_date" : ISODate("2015-09-05T20:32:16.527Z"),
            "coupons" : ObjectId("55eb10cd516ddc751d3d5e25"),
            "order_type" : [
                "in_store",
                "curbside"
            ]
        },
        {
            "item" : ObjectId("55eb10b8516ddc7508dba7cc"),
            "quantity" : 1,
            "added_date" : ISODate("2015-09-05T20:32:16.527Z"),
            "coupons" : ObjectId("55eb10cd516ddc751d3d5e25")
        },
        {
            "item" : ObjectId("55eb10b8516ddc7508dba7c8"),
            "quantity" : 1,
            "added_date" : ISODate("2015-09-05T20:32:16.527Z"),
            "coupons" : ObjectId("55eb10cd516ddc751d3d5e25")
        }
    ]
}

这是我的模型:

class CartItem(mongoengine.EmbeddedDocument):
    item = mongoengine.ReferenceField('Item')
    quantity = mongoengine.IntField()
    added_date = mongoengine.DateTimeField( default=timezone.now() )
    coupons = mongoengine.ReferenceField('Coupon')
    order_type = mongoengine.ListField(mongoengine.StringField(choices=ORDER_TYPE_CHOICES))

class Cart(mongoengine.Document):
    user = mongoengine.ReferenceField('User')
    items = mongoengine.EmbeddedDocumentListField(CartItem)
    savings = mongoengine.DecimalField(precision=2, default=0)

现在我希望能够获得 CartItems,例如只有 “in_store” 的 order_type。所以我是这样的:

cart = Cart.objects.filter(id="id")
items = cart.items
curbside_items = items.filter(order_type="curbside")

这不会返回任何东西。所以我试试这个:

curbside_items = items.filter(order_type__math="curbside")

但这也不会给我任何返回。所以我的问题是如何在 mongoengine 中执行此操作。谢谢!

最佳答案

MongoEngine 使用 "double underscore"翻译成"dot notation"的属性MongoDB 查询的形式。因此,您要查找的属性的“父级”是“项目”,这意味着您可以像这样引用完整路径:

Cart.objects.filter(items__order_type="in_store")

其中文档包含“in_store”作为 items 数组中的 order_type 条目。请注意,这将返回“整个文档”而不仅仅是匹配的条目。还有其他方法可以在响应中处理该问题。

一种方法是使用底层的 pymongo 驱动程序获得“原始”结果:

Cart._get_collection().find(
    { "items.order_type": "in_store" },
    { "items.$": 1 }
)

它利用了 positional $运算符以便仅返回匹配的数组元素。

或者对于“多个”匹配,则需要 .aggregate():

Cart._get_collection().aggregate([
    { "$match": {
        "items.order_type": "in_store"
    }},
    { "$redact": {
        "$cond": {
            "if": { "$eq": [ { "$ifNull": [ "$order_type", "in_store" ] }, "in_store" ] },
            "then": "$$DESCEND",
            "else": "$$PRUNE"
        }
    }}
])

或者通过 $filter 在未来的版本中更有意义:

Cart._get_collection().aggregate([
    { "$match": {
        "items.order_type": "in_store"
    }},
    { "$project": {
        "items": {
            "$filter": {
                "input": "$items",
                "as": "el",
                "cond": { "$eq": [ "$$el.order_type", "in_store" ] }
            }
        }
    }}
])

“djangoesque”行中的标准 mongoengine 查询不支持此类操作,并且只返回未修改的整个文档。 $slice 是个异常(exception),它可以选择执行其原生 MongoDB 对应项所做的操作。

关于python - 匹配 EmbeddedDocumentList 中的 EmbeddedDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32420464/

相关文章:

javascript - 在 Django 模板中包含 JavaScript 的最佳实践

python - 从 django 执行不能被 web 服务器中断的后台进程

django - 从python内部执行Django的sqlsequencereset代码

ruby-on-rails - 使用 MongoID 的不区分大小写的查询条件

python - 为什么 Tkinter 应用程序在调用退出后没有关闭

javascript - 在 Python 中使用回调下载 CSV

python - 如何从函数本身内部打印python函数的Docstring?

python - 从Python列表中的每个数字中减去一个值?

java - 使用 java 验证来自 MongoDB 的数据

python - 我如何在 Python/Flask 中干净地做 slugs?