聚合总和来自数组字段MongoDB的不同文档

时间:2017-01-09 20:15:00

标签: mongodb

我有一组文档,其中包含一个带有文本标记数组的字段。例如。

{
  _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
}

事先得到很多赞赏。

1 个答案:

答案 0 :(得分:1)

db.getCollection('collection').aggregate([
{
  $unwind : "$tags"
},
{
  $group: {
    _id: "$tags",
    count: {$sum: 1}}
}
])