MongoDB 聚合嵌入的数组(扁平化数据+管道)

MongoDB学习教程git

先看下要操做的主要数据结构:mongodb

{
    "_id" : "000015e0-3e9c-40b3-bd0d-6e7949f455c0",
    "evaluation_type" : 2,
    "reply_count" : 5,
    "type" : 3,
    "content" : "怎么编制余额调节表",
    "tips" : [ 
        {
            "_id" : 1000,
            "tip_name" : "会计基础"
        }
    ],
    "teach_id" : 10298153
}

看这个文档数据,如今要以 tips 数组下的 _id 作数据的分组查询。在查询条件中使用 "tips.0._id":1000 过滤数据是能够生效的,但用在 aggregate 聚合查询中的 group 分组条件中是不行的,必须得先使用 $unwind (文档地址)把 tips 这个数组对象变成扁平的结构(把数组中的每一个对象拆分出来与当前文档从新组合,达到消数组的效果)数组

上面数据根据如下查询语句的先后变化数据结构

扁平化前:app

db.getCollection('topics').find({"teach_id":10010943})


扁平化后:ide

db.getCollection('topics').aggregate({'$match':{"teach_id":10010943}},{'$unwind':'$tips'})


关注扁平化先后 tips 由数组变成了对象学习

经过 {'$unwind' : '$tips'} 对文档扁平化结构以后,而后再用 pipeline (管道)的方式作聚合就行了,lua

能够直接根据 tips._id 进行分组了spa

查询语句:code

db.getCollection('topics').aggregate({'$match':{"teach_id":10010943}},{'$unwind':'$tips'},
{'$group':{'_id':{"tipId":'$tips._id',"tipName":'$tips.tip_name',"evaluationType":'$evaluation_type'},"count":{'$sum': 1}}},
{'$project':{"tipId":'$_id.tipId',"tipName":'$_id.tipName',"evaluationType":'$_id.evaluationType',"count":'$count'}})

完美滴根据 tipId,tipName,evaluationType 分好组了

关注公众号,分享干货,讨论技术

相关文章
相关标签/搜索