0

I'm trying to count average BMI for every nationality in my database. I had to cast weight and height do double cause $avg was returning null

db.people.aggregate
(
    {
        $group:
       {
            _id:"$nationality",
            avgBMi:
            {
                $avg:
                {
                    $divide:
                    [
                        {$toDouble:"$weight",$pow:[{$toDouble:"$height"},2]}
                    ]
                }
            } 
        }
    }   
)

but im getting errors and i dont know how to deal with them

"errmsg" : "An object representing an expression must have exactly one 
field: { $toDouble: \"$weight\", $pow: [ { $toDouble: \"$height\" }, 2.0 ] }"

then I read about match and group so I made

db.people.aggregate
(
   {$group:
   {
       _id:"$nationality"
   }},
   {
       $match:{
           avgBMi:
            {
                $avg:
                {
                    $divide:
                    [
                        {$toDouble:"$weight",$pow:[{$toDouble:"$height"},2]}
                    ]
                }
            }  

       }
   }
)

and i get

"errmsg" : "unknown operator: $avg"

here's a sample of my collection

{
  "_id": {
    "$oid": "5be18d5cedc30c3a396e3651"
  },
  "sex": "Female",
  "first_name": "Frances",
  "last_name": "Romero",
  "job": "Project Manager",
  "email": "[email protected]",
   "location": {
     "city": "Yantang",
     "address": {
      "streetname": "Holy Cross",
       "streetnumber": "33801"
     }
   },
   "description": "non velit nec nisi vulputate nonummy maecenas tincidunt 
    lacus at velit",
    "height": "179.89",
    "weight": "67.8",
    "birth_date": "1954-03-25T11:51:38Z",
    "nationality": "China"
}

Can u guys please help me?

2
  • 1
    Would be a bit easier if you could supply at least one document as a sample from your people collection Commented Nov 6, 2018 at 13:31
  • what you actually want? can you please explain in more detail Commented Nov 6, 2018 at 14:01

1 Answer 1

1

You were close on your first attempt, but the weight and height conversions need to be separate objects:

db.people.aggregate([
   {$group:
   {
       _id:"$nationality",
       avgBMi:
        {
            $avg:
            {
                $divide:
                [
                    {$toDouble:"$weight"},
                    {$pow:[{$toDouble:"$height"},2]}
                ]
            }
        }             
   }}
])

Output:

{ "_id" : "China", "avgBMi" : 0.0020951525521518315 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.