mongodb 怎么 对类型为list的字段的值进行汇总统计

mongodb中有一个字段为list类型如下,tags想要对tags内的'a、b、c、d'其进行计数统计
{'_id':ObjectId('594e473dd746002ad0464b36'),'tags':['a','b','d']}
{'_id':ObjectId('59637962d7460028c05590ef'),'tags':['a','c','d']}
{'_id':ObjectId('59637962d7460028c0558ff6'),'tags':['c','d']}
统计tags内的'a','b','c','d'每个都出现了几次。期待的结果
[{'name':'a','count':2},
{'name':'b','count':1},
{'name':'c','count':2},
{'name':'d','count':3}]
该怎么写这个查询语句呢?
慕哥6287543
浏览 2043回答 2
2回答

哆啦的时光机

数据源db.getCollection('test').insert([{'tags':['a','b','d']},{'tags':['a','d']},{'tags':['b','d']}])SQLdb.getCollection('test').aggregate([{$unwind:'$tags'},{$group:{_id:'$tags',count:{$sum:1}}}])结果/*1*/{"_id":"d","count":3.0}/*2*/{"_id":"b","count":2.0}/*3*/{"_id":"a","count":2.0}如果你要将查询结果的_id字段名改为name,那么就要再加个$projectdb.getCollection('test').aggregate([{$unwind:'$tags'},{$group:{_id:'$tags',count:{$sum:1}}},{$project:{_id:0,name:'$_id',count:'$count'}}])

翻翻过去那场雪

db.collection.aggregate([{$unwind:"$tags"},{$group:{_id:"$tags",count:{$sum:1}}},{$project:{name:"$_id",count:"$count",_id:0}}]);$unwind,$group,$project都是很常用的运算符,先查下文档看咯,不懂再说。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript