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}]该怎么写这个查询语句呢?
2 回答

哆啦的时光机
TA贡献1779条经验 获得超6个赞
数据源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'}}])

翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
db.collection.aggregate([{$unwind:"$tags"},{$group:{_id:"$tags",count:{$sum:1}}},{$project:{name:"$_id",count:"$count",_id:0}}]);$unwind,$group,$project都是很常用的运算符,先查下文档看咯,不懂再说。
添加回答
举报
0/150
提交
取消