MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Mongodb - $group à l'intérieur d'un $group (par 'key')

Vous pouvez ajouter des $cond imbriqués pour filtrer les clés 123 ou 456. Ensuite, un dernier $project stage peut être utilisé pour construire le tableau.

db.events.aggregate([
    {"$group":
        {   "_id":"$KLLS",
            "Processus":{"$push":{"$cond":[{"$eq":["$type","Processus"]},'$$ROOT',false]}},
            "Work123":
                {"$push":
                    {"$cond":
                        [
                            {"$eq":["$type","Work"]},
                            {"$cond":
                                [
                                    {"$eq":["$key","123"]},
                                    '$$ROOT',
                                    false
                                ]
                            },
                            false
                        ]
                    }
                },
            "Work456":
                {"$push":
                    {"$cond":
                        [
                            {"$eq":["$type","Work"]},
                            {"$cond":
                                [
                                    {"$eq":["$key","456"]},
                                    '$$ROOT',
                                    false
                                ]
                            },
                            false
                        ]
                    }
                },
            "Viewing":{"$push":{"$cond":[{"$eq":["$type","Viewing"]},'$$ROOT',false]}}
        }
    },
    {"$project": { "_id":0, "KLLS":"$_id", "Processus":{"$setDifference":["$Processus",[false]]},
        "123":{"$setDifference":["$Work123",[false]]},
        "456":{"$setDifference":["$Work456",[false]]},
        "Viewing":{"$setDifference":["$Viewing",[false]]}
        }
    },
    {"$project": { "KLLS":1, "Processus":1, "Work" : [{"123" : "$123"}, {"456" : "$456"}],"Viewing":1}}
])