[英]MongoDB aggregation avg-function
I'm trying to count average weight and height for every gender in my database.我正在尝试计算数据库中每个性别的平均体重和身高。 I had to group it by gender but $avg
was returning null on both weight and height.我必须按性别对其进行分组,但$avg
在体重和身高上都返回 null。 Any ideas how to fix it?任何想法如何解决它?
db.getCollection("people").aggregate(
[
{
$group: {
_id: { sex: "$sex" },
avgH: { $avg: "$height" },
avgW: { $avg: "$weight" }
}
}
]
);
Sample of data model:数据样本 model:
{
"_id" : ObjectId("5ea970747cd4ac05869977ec"),
"sex" : "Male",
"first_name" : "Wayne",
"last_name" : "Fields",
"job" : "Speech Pathologist",
"email" : "wfields0@diigo.com",
"location" : {
"city" : "Oyo",
"address" : {
"streetname" : "Beilfuss",
"streetnumber" : "860"
}
},
"description" : "vulputate justo in blandit ultrices enim lorem ipsum dolor sit amet consectetuer adipiscing elit proin interdum mauris",
"height" : "152.38",
"weight" : "66.81",
"birth_date" : "1990-02-21T02:55:03Z",
"nationality" : "Nigeria",
"credit" : [
{
"type" : "switch",
"number" : "6759888939100098699",
"currency" : "COP",
"balance" : "5117.06"
}
]
}
As per documentation :根据文档:
$avg ignores non-numeric values. $avg 忽略非数字值。
you need to convert weight
and height
from string
to double
using $toDouble (MongoDB 4.0 or newer):您需要使用$toDouble (MongoDB 4.0 或更高版本)将weight
和height
从string
转换为double
精度:
db.collection.aggregate([
{
$group: {
_id: { sex: "$sex" },
avgH: { $avg: { $toDouble: "$height" } },
avgW: { $avg: { $toDouble: "$weight" } },
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.