Mongodb group and sort

Viewed 85075

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

select a,b,sum(c) csum from coll where active=1 group by a,b order by a

Is there any way to execute a group and sort query with Mongo?

9 Answers

Adding to previous answers, if you want to sort on the sum (the result of the aggregate) instead of on the actual column, you can do this:

db.your_collection.aggregate([
    {
        $group: {_id: "$your_document_name", count: {$sum: 1}}
    }, 
    {
        $sort: {"count":-1}
    }
])

This would be the equivalent of the following standard-SQL-ish syntax:

select col_a, count(col_a) as b
from table
group by col_a
order by b desc

you can use the $group and $sort in aggregate in the order $group > $sort . Using the sort before group won't work. Consider the example below:

let data = await ABCModel.aggregate([
      {
        $match: { city: { $nin: ['', null] }},
      },
      {
        $group: {
          _id: { $toLower: '$city' }
        },
      },
      { $sort: { _id: 1 } },
    ]);

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
}       
Related