Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use sum, multiply, divide and group by aggregation in single mongodb query

Tags:

mysql

mongodb

I have following mysql query in which I have done sum on two different fields called "count" and "population" and then divided sum(count)/sum(population) and then multiplied it with 100000 and finally grouping it by year.

Select year, cname, (sum(count)/sum(population))*100000 as total from cancer c where c.cname ="lung and bronchus" group by year;

I have written following query in mongodb but I am not sure how to project cname and year.

db.cancer_stats.aggregate([
       {$match:{cname: "lung and bronchus"}},
       {$group:{_id:"year"},
               {total:{$multiply:[$divide:[$sum:"$count", $sum:"population"], 100000]}}
        }])

can anyone guide me in solving this query?

like image 749
Yash Avatar asked Dec 08 '14 06:12

Yash


People also ask

Can we specify more than one aggregate function simultaneously in MongoDB?

Db. collection. aggregate () can use several channels at the same time for data processing.

How do I multiply two fields in MongoDB?

Multiplies numbers together and returns the result. Pass the arguments to $multiply in an array. The $multiply expression has the following syntax: { $multiply: [ <expression1>, <expression2>, ... ] }

How aggregation is performed in MongoDB?

In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.

Can we use $and in aggregate MongoDB?

You can use $and with aggregation but you don't have to write it, and is implicit using different filters, in fact you can pipe those filters in case one of them needs a different solution.


1 Answers

I'm not sure what you mean by "solving the query", but that query is not valid in its current form. I think you want a pipeline like the following:

db.cancer_stats.aggregate([
    { "$match" : { "cname" : "lung and bronchus" } },
    { "$group" : { "_id" : "year", "t_count" : { "$sum" : "$count" }, "t_population" : { "$sum" : "$population" } } },
    { "$project" : { "result" : { "$multiply" : [100000, { "$divide" : ["$t_count", "$t_population"] } ] } } }
])

Does that answer your question?

like image 184
wdberkeley Avatar answered Oct 16 '22 08:10

wdberkeley