sql >> Database >  >> NoSQL >> MongoDB

Mongodb - $groep binnen een $groep (op 'sleutel')

U kunt geneste $cond . toevoegen om de sleutels 123 of 456 te filteren. Dan, een laatste $project stage kan worden gebruikt om de array te construeren.

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



  1. Aan de slag met Python en MongoDB

  2. Kan MongoDB werken als de database groter is dan RAM?

  3. Mongo db-aggregatie meerdere voorwaarden

  4. Hoe mongodb groeperen - mapReduce output?