• ADADADADAD

    mongodb中aggregate()有什么用[ 建站问答 ]

    建站问答 时间:2024-12-01 18:57:17

    作者:文/会员上传

    简介:

    mongodb中aggregate()的作用:在mongodb中aggregate()主要是用来处理数据并返回计算后的数据结果,比如统计平均值,求和等运算操作,aggregate()的语法如:“db.COLLECTION_NAME.aggr

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    mongodb中aggregate()的作用:在mongodb中aggregate()主要是用来处理数据并返回计算后的数据结果,比如统计平均值,求和等运算操作,aggregate()的语法如:“db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)”。

    具体内容如下:

    aggregate() 方法的基本语法格式如下所示

    >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

    实例

    集合中的数据如下:

    {

    _id:ObjectId(7df78ad8902c)

    title:'MongoDBOverview',

    description:'MongoDBisnosqldatabase',

    by_user:'runoob.com',

    url:'http://www.runoob.com',

    tags:['mongodb','database','NoSQL'],

    likes:100

    },

    {

    _id:ObjectId(7df78ad8902d)

    title:'NoSQLOverview',

    description:'Nosqldatabaseisveryfast',

    by_user:'runoob.com',

    url:'http://www.runoob.com',

    tags:['mongodb','database','NoSQL'],

    likes:10

    },

    {

    _id:ObjectId(7df78ad8902e)

    title:'Neo4jOverview',

    description:'Neo4jisnosqldatabase',

    by_user:'Neo4j',

    url:'http://www.neo4j.com',

    tags:['neo4j','database','NoSQL'],

    likes:750

    },

    现在我们通过以上集合计算每个作者所写的文章数,使用aggregate()计算结果如下:

    >db.mycol.aggregate([{$group:{_id:"$by_user",num_tutorial:{$sum:1}}}])

    {

    "result":[

    {

    "_id":"runoob.com",

    "num_tutorial":2

    },

    {

    "_id":"Neo4j",

    "num_tutorial":1

    }

    ],

    "ok":1

    }

    >

    以上实例类似sql语句:

    selectby_user,count(*)frommycolgroupbyby_user

    在上面的例子中,我们通过字段 by_user 字段对数据进行分组,并计算 by_user 字段相同值的总和。

    下表展示了一些聚合的表达式:

    mongodb中aggregate()有什么用.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: mongodbaggregate