1
I have a collection
in the MongoDB
and it has several records and I need to sum up a column by UF and then return the highest value of that sum. For example
UF: 'SP',
Valor: 10
----
UF: 'SP',
Valor: 23.5
----
UF: 'RJ',
Valor: 40
----
UF: 'PR',
Valor: 5
What I need to do is add the values by the state, that is to say:
SP = 33.5
RJ = 40
PR = 5
And return the higher value than in the case:
40 (que é de RJ)
All this with mongoDB. I’m using PHP, but it doesn’t interfere. The problem is in query
that I don’t know how to do correctly. I tried to do one that looked like this but it didn’t work, just returned the maximum number of each state:
{
{
'$group' : {
'_id' : '$UF',
'Maximo' : {
$max: {
{'$sum' : '$Valor'}
}
}
}
}
What I need is to return the maximum number of the sum, not all, only the highest of all sums. This I would like to do without having to give foreach
in PHP, so I wanted to do everything in the query now.
In this second example it will return the sum value per state. What I wanted is that after he did this, then he would return only the highest value and not all.
– Alisson Acioli
@Alissonacioli you want moreover a limit and an ordernation? would that in the second example?
– novic
@Alissonacioli has 3 answers the last one I believe serves for your purpose, take a check?
– novic
In the second example you do 50% of what I want is to add the value of the "Value" column according to each state. Let’s assume that it returns 5 states, each with a different "Count" (state sum). I want to know which of these 5 states has the largest sum and bring only it.
– Alisson Acioli
From what I saw, your last answer might work for me. Jaja I will test and return here
– Alisson Acioli
@Alissonacioli some solution worked for you?
– novic