Reputation: 299
I have performed the following query:
db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum: {$sum: 1}}},
{$sort : {sum : -1}}
);
which returns the following:
{
"_id" : {
"conso" : "x",
"region" : 1
},
"sum" : 73226.0
},
{
"_id" : {
"conso" : "x",
"region" : 8
},
"sum" : 25683.0
},
{
"_id" : {
"conso" : "grandlait demi �cr�m� uht",
"region" : 1
},
"sum" : 251.0
}
There are 21 different regions and I am trying to get the most consumed item by region. How could I use "sum" to return the highest value given each region?
Upvotes: 0
Views: 23
Reputation: 10918
It should be enough for you to add the following two stages to the end of your aggregation pipeline:
$group: {
_id: "$_id.region",
"conso": {
$first: "$_id.conso"
},
"sum": {
$first: "$sum"
}
}
Upvotes: 1