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?
Just sort on avgprice, and limit to one doc.
[
{ $match: { Make: 'Honda' } },
{
$group: {
_id: '$Type',
avgcost: { $avg: '$Price' }
}
},
{$sort: {avgcost: -1}},
{$limit: 1}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With