MongoDB nested group?

后端 未结 2 1629
终归单人心
终归单人心 2020-12-23 22:36

I\'m trying to implement a nested group query in mongodb and I\'m getting stuck trying to add the outer group by. Given the below (simplified) data document:



        
2条回答
  •  独厮守ぢ
    2020-12-23 23:33

    Query:

        db.getCollection('orders').aggregate([
        {$match:{
            tipo: {$regex:"[A-Z]+"}
            }
        },
        {$group:
            { 
                _id:{
                    codigo:"1",
                    tipo:"$tipo",
                },
                total:{$sum:1}
            }
        },
        {$group:
            {
                _id:"$_id.codigo",
                tipos:
                {
                    $push:
                    {
                        tipo:"$_id.tipo",
                        total:"$total"
                    }
                },
                totalGeneral:{$sum:"$total"}
    
            }
    
        }
    
    
    ]);
    

    Response:

    {
    "_id" : "1",
    "tipos" : [ 
        {
            "tipo" : "TIPO_01",
            "total" : 13.0
        }, 
        {
            "tipo" : "TIPO_02",
            "total" : 2479.0
        }, 
        {
            "tipo" : "TIPO_03",
            "total" : 12445.0
        }, 
        {
            "tipo" : "TIPO_04",
            "total" : 12445.0
        }, 
        {
            "tipo" : "TIPO_05",
            "total" : 21.0
        }, 
        {
            "tipo" : "TIPO_06",
            "total" : 21590.0
        }, 
        {
            "tipo" : "TIPO_07",
            "total" : 1065.0
        }, 
        {
            "tipo" : "TIPO_08",
            "total" : 562.0
        }
    ],
    "totalGeneral" : 50620.0
    

    }

提交回复
热议问题