Reputation: 1
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?
Upvotes: 0
Views: 665
Reputation: 312115
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 }
Upvotes: 1