Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database MongoDB聚合平均函数_Database_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

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" } },
        }
    }
])