素材牛VIP会员
mongodb 怎么 对类型为list的字段的值进行汇总统计
 飞***a  分类:Python  人气:918  回帖:4  发布于6年前 收藏

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

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

讨论这个帖子(4)垃圾回帖将一律封号处理……

Lv1 新人
青***8 页面重构设计 6年前#1

数据源

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'
    }
}
])
Lv6 码匠
问***m Linux系统工程师 6年前#2

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

Lv5 码农
ch***am PHP开发工程师 6年前#3

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

Lv5 码农
wz***16 技术总监 6年前#4
db.collection.aggregate([
    {$unwind: "$tags"},
    {$group: {_id: "$tags", count: {$sum: 1}}},
    {$project: {name: "$_id", count: "$count", _id: 0}}
]);

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取