mongodb math operations on two fields in collection

Viewed 25

Hello i have exercise to filter all countries where gdp is greater than 0.05 on one person in country. I need to take the latest year of population. Also code of the country should have at least 3 characters. My collection looks like this:

mondial.countries
{
    "_id" : ObjectId("581cb5a519ec2deb4ba71c03"),
    "name" : "Germany",
    "code" : "GER",
    "capital" : "RN-Niamey-Niamey",
    "area" : 1267000,
    "gdp" : 7304,
    "inflation" : 1.9,
    "unemployment" : null,
    "independence" : ISODate("1960-08-03T00:00:00Z"),
    "government" : "republic",
    "population" : [
        {
            "year" : 1950,
            "value" : 2559703
        },
        {
            "year" : 1960,
            "value" : 3337141
        },
        {
            "year" : 1970,
            "value" : 4412638
        },
        {
            "year" : 1977,
            "value" : 5102990
        },
        {
            "year" : 1988,
            "value" : 7251626
        },
        {
            "year" : 1997,
            "value" : 9113001
        },
        {
            "year" : 2001,
            "value" : 11060291
        },
        {
            "year" : 2012,
            "value" : 17138707
        }
    ]
}

For this example I have to take the population from year 2012 a divide it by gdp a then display it if its greater than 50000. I have been trying with function in js but idk how to show fields that are greater thatn 5000 of my operation. What is the easies way to do this?

var countries = db.mondial.countries.find({
"code": {$gte: 3},
});

while(countries.hasNext()) {
    gdp = countries.next()
    gdpresult = countries.population / gdp.gdp
    
    print(gdpresult)
    
    }

1 Answers

I don't know if I understood correctly. more see if it helps

db.mondial.aggregate([
{
    $match:{
         $expr: {
             $gte:['$code',3 ]
         }
    }
},
{
    $project: {
        gdpresult: {
            $map: {
                input: '$population',
                as: 'p',
                in: {
                    value: {
                        $divide: ["$$p.value", '$gdp']
                    },
                    year: '$$p.year'
                }
            }
        }
    }
}])
Related