Search code examples
mongodbnosqlaggregation-frameworknosql-aggregation

MongoDB Shell How can I average or $min/$max a sum of strings


I've been trying to get my head around aggregation for a while now and I can't seem to work out how to find the average, min or max, of a sum of strings.

    db.mycollectionname.aggregate([
    {$unwind: "$Monitor"},
        {$group: {_id: "$Monitor.Mon Type",
        "Total": {$sum: 1}
        }
    }
])

I know it's not much, but this is how far I managed to get, it pumps out this;

{ "_id" : "RM", "Total" : 21 }
{ "_id" : "PT", "Total" : 43 }
{ "_id" : "IM", "Total" : 24 }
{ "_id" : "IO", "Total" : 72 }

What I'm trying to do is get the min/max of these sum results and an average of all the results. Any help or advice is appreciated, can't seem to find anything that helps me out. Thank you


Solution

  • Add this stage as last stage :

    {$group :{_id:'', minimum :{$min: '$Total'}, maximum :{$max: '$Total'}, Total :{$sum : '$Total'}, average :{$avg : '$Total'}}}
    

    So your query :

    db.mycollectionname.aggregate([
        { $unwind: "$Monitor" },
        {
            $group: {
                _id: "$Monitor.Mon Type",
                "Total": { $sum: 1 }
            }
        },
        {
            $group: {
                _id: '', minimum: { $min: '$Total' }, maximum: { $max: '$Total' },
                Total: { $sum: '$Total' }, average: { $avg: '$Total' }
            }
        }
    ])
    

    So when you do _id: '' or _id: null, a group stage would iterate through all the documents at that point. After adding final $group stage result should be :

    /* 1 */
    {
        "_id" : "",
        "minimum" : 21.0,
        "maximum" : 72.0,
        "Total" : 160.0,
        "average" : 40.0
    }