MongoDB nested group?

后端 未结 2 1615
终归单人心
终归单人心 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:27

    You will need two groups in this case. The first group generates a stream of documents with one document per term and category:

     { $group : { 
          _id :  { 
            category: "$category",
            term: "$term",
          },
          total: { $sum : 1 } 
       }
     }
    

    A second group will then merge all documents with the same term into one, using the $push operator to merge the categories into an array:

     { $group : { 
          _id :  "$_id.category",
          terms: { 
              $push: { 
                  term:"$_id.term",
                  total:"$total"
              }
          }
       }
     }
    
    0 讨论(0)
  • 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
    

    }

    0 讨论(0)
提交回复
热议问题