lucianovalenca
9/9/2019 - 12:40 PM

match in lookup result

// Requires official MongoShell 3.6+
use webapp;
db.getCollection("schools").aggregate(
    [
        { 
            "$match" : {
                "status" : "active", 
                "country" : "Reino Unido", 
                "city" : "Londres"
            }
        }, 
        { 
            "$group" : {
                "_id" : "$_id", 
                "school" : {
                    "$push" : "$$ROOT"
                }
            }
        }, 
        { 
            "$unwind" : {
                "path" : "$school"
            }
        }, 
        { 
            "$lookup" : {
                "from" : "hosting", 
                "localField" : "_id", 
                "foreignField" : "schoolId", 
                "as" : "hosting"
            }
        }, 
        { 
            "$lookup" : {
                "from" : "courses", 
                "as" : "courses", 
                "let" : {
                    "schoolId" : "$_id"
                }, 
                "pipeline" : [
                    {
                        "$match" : {
                            "$expr" : {
                                "$and" : [
                                    {
                                        "$eq" : [
                                            "$schoolId", 
                                            "$$schoolId"
                                        ]
                                    }, 
                                    {
                                        "$eq" : [
                                            "$program", 
                                            "Intensivo"
                                        ]
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);