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}]
该怎么写这个查询语句呢?
数据源
db.getCollection('test').insert([
{
'tags':['a','b','d']
},
{
'tags':['a','d']
},
{
'tags':['b','d']
}
])
SQL
db.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,那么就要再加个$project
db.getCollection('test').aggregate([
{
$unwind: '$tags'
},{
$group: {
_id: '$tags',
count: {$sum: 1}
}
},{
$project: {
_id:0,
name: '$_id',
count: '$count'
}
}
])