数组字段MongoDB中不同文档的聚合和
我有一组文档,其中有一个带有文本标记数组的字段。例如数组字段MongoDB中不同文档的聚合和,mongodb,Mongodb,我有一组文档,其中有一个带有文本标记数组的字段。例如 { _id: uXFLH__St8o3NfxwMa53ig, tags: ['foo', 'bar', 'foobar'] }, { _id: DWbe__3fegKXBa_Ai3CGRQ, tags: ['foo', 'bar'] } 我想获得整个集合中这些标记的不同出现次数的计数,以便输出是 { "_id": "foo", count: 2 }, { "_id": "bar", count: 2 }, {
{
_id: uXFLH__St8o3NfxwMa53ig,
tags: ['foo', 'bar', 'foobar']
},
{
_id: DWbe__3fegKXBa_Ai3CGRQ,
tags: ['foo', 'bar']
}
我想获得整个集合中这些标记的不同出现次数的计数,以便输出是
{
"_id": "foo",
count: 2
},
{
"_id": "bar",
count: 2
},
{
"_id": "foobar",
count: 1
}
我尝试过聚合(我也有一些复杂的$match步骤),但不知道如何获得上面的输出。此查询:
db.getCollection('collection').aggregate([
{$group: {_id: "$tags", count: {$sum: 1}}}
])
产生以下结果:
{
"_id" : ['foo', 'bar']
"count" : 1.0
},
{
"_id" : ['foo', 'bar', 'foobar']
"count" : 1.0
}
非常感谢。您错过了
$unwind
步骤<代码>{$unwind:“$tags”}在组之前。是的,就是这样。谢谢它总是很小的东西。泰
db.getCollection('collection').aggregate([
{
$unwind : "$tags"
},
{
$group: {
_id: "$tags",
count: {$sum: 1}}
}
])