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?
Db. collection. aggregate () can use several channels at the same time for data processing.
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>, ... ] }
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.
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.
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?
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