MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb - $group innerhalb einer $group (durch 'key')

Sie können verschachteltes $cond hinzufügen um die Schlüssel 123 oder 456 zu filtern. Dann ein letztes $project stage kann verwendet werden, um das Array zu erstellen.

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