【问题标题】:Mongodb how to find all subdocuments that match a criteriaMongodb如何找到所有符合条件的子文档
【发布时间】:2019-04-10 22:32:02
【问题描述】:

我正在尝试查询符合子文档/对象中条件的所有文档。

如何创建一个查询来查找所有匹配的子文档/对象?

这是收藏:

document = { _id: ObjectId("..."),
            product: "ABC", 
            actions: [
                {
                    customer: "Foo",
                    status: "SOLD"
                },
                {
                    customer: "Bar",
                    status: "NOT SOLD"
                },
                {
                    customer: "John", 
                    status: "SOLD"
                },
                {
                    customer: "Doe", 
                    status: "WAITING"
                }
            ]
        }

这是我的代码,它返回所有具有一个 actions.status = SOLD 的文档,但它只返回操作中的第一个子文档。

    def query(collection):
        """
        Find all products that have been sold to one or more customers
        """
        query = {"actions.status":"SOLD"}
        options = {"product":1, "actions.$":1}

        res = collection.find(query, options)

我想要的输出是所有产品和所有状态 = SOLD 的客户,但我的查询只返回第一个状态 = SOLD 的客户。

所以我想要的是

    document = { _id: ObjectId("..."),
            product: "ABC", 
            actions: [
                {
                    customer: "Foo",
                    status: "SOLD"
                }, 
                {
                    customer: "John", 
                    status: "SOLD"
                }
            ]
        }

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    尝试如下:

    db.collection.aggregate([
        {
            $project: {
                product:1,
                actions: {
                    $filter: {
                        input: "$actions",
                        as: "act",
                        cond:  { $eq: ["$$act.status", 'SOLD' ] }
                    }
                }
            }
        }    
    ])
    

    结果:

    {
        "_id" : ObjectId("5cadfaff3d124a151f633af7"),
        "product" : "ABC",
        "actions" : [
            {
                "customer" : "Foo",
                "status" : "SOLD"
            },
            {
                "customer" : "John",
                "status" : "SOLD"
            }
        ]
    }
    

    【讨论】:

      【解决方案2】:

      MongoDB 无法在 standard query 中“过滤”此内容。MongoDB 实际上必须执行此级别 manipulation is with the aggregation framework 的唯一工具。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-25
        • 2017-04-24
        • 2017-12-09
        • 1970-01-01
        • 2014-01-14
        • 2018-04-02
        • 2019-12-30
        • 2023-03-30
        相关资源
        最近更新 更多