MongoDB聚合问题

时间:2018-11-06 13:27:50

标签: mongodb aggregation-framework

我正在尝试在数据库中计算每个国籍的平均BMI。我不得不投下体重和身高,原因是$ avg返回null

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

但是我遇到了错误,我不知道该如何处理

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

然后我了解了比赛和分组,所以我做了

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

       }
   }
)

我得到

"errmsg" : "unknown operator: $avg"

这是我收藏的样品

{
  "_id": {
    "$oid": "5be18d5cedc30c3a396e3651"
  },
  "sex": "Female",
  "first_name": "Frances",
  "last_name": "Romero",
  "job": "Project Manager",
  "email": "fromeroc@ted.com",
   "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"
}

你们能帮我吗?

1 个答案:

答案 0 :(得分:1)

您的初次尝试很接近,但是体重和身高的转换必须是单独的对象:

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

输出:

{ "_id" : "China", "avgBMi" : 0.0020951525521518315 }