seki
seki

Reputation: 89

How to use nested mongoDB query to calculate percentage?

It is our coursework today, this is the dataset, and this is the column description:

VARIABLE DESCRIPTIONS:
Column
   1     Class (0 = crew, 1 = first, 2 = second, 3 = third)
  10     Age   (1 = adult, 0 = child)
  19     Sex   (1 = male, 0 = female)
  28     Survived (1 = yes, 0 = no)

and the last question is

What percentage of passenger survived? (use a nested mongodb query)

I know if I am going to calculate the percentage, I use .count to find how many rows that Survive = 1, and how many rows in total and use .find(Survive:1).count() divide .find().count() , for now I know I can use aggregate to solve the problem but it does not meet the requirement. Any ideas?

Upvotes: 1

Views: 374

Answers (1)

mickl
mickl

Reputation: 49975

Considering following data:

db.titanic.insert({ Survived: 1 })
db.titanic.insert({ Survived: 1 })
db.titanic.insert({ Survived: 1 })
db.titanic.insert({ Survived: 0 })

you can use $group with $sum. 1 passed as a argument will give you total count while $Survived will count survived people. Then you can use $divide to get the percentage.

db.titanic.aggregate([
    {
        $group: {
            _id: null,
            Survived: { $sum: "$Survived" },
            Total: { $sum: 1 }
        }
    },
    {
        $project: {
            _id: 0,
            SurvivedPercentage: { $divide: [ "$Survived", "$Total" ] }
        }
    }
])

which outputs: { "SurvivedPercentage" : 0.75 }

Upvotes: 3

Related Questions