• MongoDB 聚合管道(aggregate)


    1、aggregate() 方法

    我们先插入一些测试数据

    { 
        "_id" : ObjectId("5abc960c684781cda6d38027"), 
        "name" : "郭大爷", 
        "sex" : "男", 
        "age" : 80.0, 
        "skil" : [
            "PHP", 
            "Js", 
            "MySql", 
            "Html", 
            "Css"
        ]
    }
    { 
        "_id" : ObjectId("5abc960c684781cda6d38028"), 
        "name" : "郭大爷", 
        "sex" : "男", 
        "age" : 60.0, 
        "skil" : [
            "PHP", 
            "MySql"
        ]
    }
    { 
        "_id" : ObjectId("5abc960c684781cda6d38029"), 
        "sex" : "女", 
        "age" : 15.0, 
        "name" : "郭女侠"
    }
    { 
        "_id" : ObjectId("5abc960c684781cda6d3802a"), 
        "name" : "郭少爷", 
        "sex" : "男", 
        "age" : 18.0, 
        "skil" : [
            "Css", 
            "Java", 
            "Html"
        ]
    }
    • 求和 

    查询一下所有人年龄的总和

    db.userinfo.aggregate([
        { $group : {
            _id : null,
            age_sum : { $sum : "$age" }
        }}
    ])

    结果

    { 
        "_id" : null, 
        "age_sum" : 173.0
    }
    • 平均值

    求所有人年龄的平均值

    db.userinfo.aggregate([
        {
            $group:{
                _id: null,
                age_avg: { $avg: "$age" }
            }
        }
    ]);

    结果

    { 
        "_id" : null, 
        "age_avg" : 43.25
    }
    • 最小值

    db.userinfo.aggregate([
        {
            $group: {
                _id: null,
                age_min: { $min: "$age" }
            }
        }
    ]);

    结果

    { 
        "_id" : null, 
        "age_min" : 18.0
    }
  • 相关阅读:
    每日一题(文化课)一题---------19/7/30
    XXXXX,这个域名
    CF1037E. Trips
    bzoj3124: [Sdoi2013]直径 树形dp two points
    luogu P3952 时间复杂度 模拟
    AGC016D
    CF444E. DZY Loves Planting
    模拟赛
    HDU 3949 XOR [线性基|高斯消元]
    博客搬家
  • 原文地址:https://www.cnblogs.com/handsCool/p/8669811.html
Copyright © 2020-2023  润新知