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}]

该怎么写这个查询语句呢?

阅读 6.7k
4 个回答

数据源

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'
    }
}
])
db.collection.aggregate([
    {$unwind: "$tags"},
    {$group: {_id: "$tags", count: {$sum: 1}}},
    {$project: {name: "$_id", count: "$count", _id: 0}}
]);

$unwind, $group, $project都是很常用的运算符,先查下文档看咯,不懂再说。

感觉写个脚本遍历比较方便,单靠写查询应该很难。

改正下 @张淞 大哥的答案,$group 阶段的count:1 应改为
count:{ $sum:1}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题