Database MongoDB聚合平均函数
我试图计算数据库中每个性别的平均体重和身高。我不得不按性别分组,但体重和身高的平均值都返回空值。有没有办法解决这个问题Database MongoDB聚合平均函数,database,mongodb,mongodb-query,aggregation-framework,Database,Mongodb,Mongodb Query,Aggregation Framework,我试图计算数据库中每个性别的平均体重和身高。我不得不按性别分组,但体重和身高的平均值都返回空值。有没有办法解决这个问题 db.getCollection("people").aggregate( [ { $group: { _id: { sex: "$sex" }, avgH: { $avg: "$height" }, avgW: { $avg: "$w
db.getCollection("people").aggregate(
[
{
$group: {
_id: { sex: "$sex" },
avgH: { $avg: "$height" },
avgW: { $avg: "$weight" }
}
}
]
);
数据模型示例:
{
"_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"
}
]
}
根据:
$avg忽略非数值
您需要使用(MongoDB 4.0或更新版本)将重量
和高度
从字符串
转换为双精度
:
您能展示一下您的数据模型吗?当然可以,有问题的话请更新,谢谢
db.collection.aggregate([
{
$group: {
_id: { sex: "$sex" },
avgH: { $avg: { $toDouble: "$height" } },
avgW: { $avg: { $toDouble: "$weight" } },
}
}
])