Mongodb如何查找符合条件的所有子文档

时间:2019-04-10 14:05:01

标签: mongodb

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

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

这是收藏集:

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

这是我的代码,返回具有一个动作的所有文档。状态=已售,但它仅返回动作中的第一个子文档。

    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"
                }
            ]
        }

2 个答案:

答案 0 :(得分:0)

尝试如下:

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"
        }
    ]
}

答案 1 :(得分:0)

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