【问题标题】:Performing Repeated filtering in mongodb在 mongodb 中执行重复过滤
【发布时间】:2020-12-03 10:06:51
【问题描述】:

我想获取在 bmw 工作的人的姓名,并使用这些姓名作为过滤器来查找并返回包含字段“car”的文档。所以最终结果必须是本例中给出的最后两个文档。

[
    {"_id": "235", "name": "indu", "dob": "31/4/15", "company": "bmw"},
    {"_id": "236", "name": "prith", "dob": "01/4/98", "company": "bmw"},
    {"_id": "237", "name": "rames", "dob": "07/4/00", "company": "renault"},
    {"_id": "238", "name": "indu", "salary": "10,000", "car": "yes", "married": "yes"},
    {"_id": "239", "name": "prith", "salary": "80,000", "car": "yes", "children": "no"}
]

感谢您的帮助,在此先感谢

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework pymongo pymongo-3.x


    【解决方案1】:

    你想使用$exists

    names = db.collection.distinct{"name", {"company": "bmw"})
    db.collection.find({"car": {"$exists": true}, "name": {"$in": names}})
    

    你也可以在 1 个聚合调用中完成,但我不推荐它,因为它的效率较低。

    db.collection.aggregate([
        {
           "$match": {
               "company": "bmw"
           }   
        },
        {
            $lookup: {
                from: "this_collection",
                localField: "name",
                foreignField: "name",
                as: "roots"
            }
        },
        {
            "$unwind": "$roots"
        },
        {
            "$replaceRoot": {
                "newRoot": "$roots"
            }
        },
        {
            "$match": {
                "car": {"$exists": true}
            }
        }
    ])
    

    【讨论】:

    • 不错的解决方案..解决了我的问题..谢谢汤姆
    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2020-03-02
    • 2016-01-13
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多