Mongodb group and sort

前端 未结 8 2119
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 15:31

How can I translate the following Sql query for Mongo?:

select a,b,sum(c) csum from coll wh         


        
8条回答
  •  独厮守ぢ
    2020-12-09 16:07

    I want to add the following query, as an example, it may be useful in case of two groupings.

    Query:

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

    Response:

    {
    "_id" : "1",
    "fechasAltas" : [ 
        {
            "fechaAlta" : "1940-01-01",
            "total" : 13.0
        }, 
        {
            "fechaAlta" : "2007-05-14",
            "total" : 115.0
        }, 
        {
            "fechaAlta" : "2008-09-30",
            "total" : 58.0
        }, 
    
        .
        .
        .
    ],
    "totalGeneral" : 50620.0
    }       
    

提交回复
热议问题