Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregation Query on MongoDB

I'm trying to do an aggregation query on a MongoDB database containing a list of different makes of motorbikes and types for each. My first query, to obtain an average price of all Honda's is working

db.bikes.aggregate([
    { $match: { Make: 'Honda' } },
    {
        $group: {
            _id: '$Type',
            avgcost: { $avg: '$Price' }
        }
    },
    {
        $group: {
            _id: '$_id.Type',
            maxavg: { $max: '$avgprice' } 
        }
    }
])

To give

{ "_id" : "VFR700", "avgprice" : 3765.23 }
{ "_id" : "Fireblade", "avgprice" : 4816.27 }
{ "_id" : "CB1000", "avgprice" : 3993.26 }
{ "_id" : "Goldwing", "avgprice" : 4193.22 }

I'm then trying to do another query, to get just the maximum average price of Honda bikes (i.e. Fireblade, "avgprice": 4816).

I'm using the following query:

db.bikes.aggregate([
    { $match: { Make: 'Honda' } },
    {
        $group: {
            _id: '$Type',
            avgcost: { $avg: '$Price' }
        }
    },
    {
        $group: {
            _id: '$_id.Type',
            maxavg: { $max: '$avgprice' }
        }
    }
])

However i'm getting

{ "_id" : null, "maxavg" : 4816.27 }

Any ideas how I can list it as I'd like i.e. with the Type name in there too?

like image 802
woody147 Avatar asked Jan 18 '26 04:01

woody147


1 Answers

Just sort on avgprice, and limit to one doc.

[
{ $match: { Make: 'Honda' } },
{
    $group: {
        _id: '$Type',
        avgcost: { $avg: '$Price' }
    }
},
{$sort: {avgcost: -1}},
{$limit: 1}

]
like image 92
hyades Avatar answered Jan 19 '26 20:01

hyades



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!