使用MongoDB获取数组中值的键值聚合?

时间:2020-06-12 18:25:47

标签: mongodb mongoose

我有一个用于博客帖子的MongoDB模式,如下所示:

{
  title: String,
  date: Date,
  description: String,
  tags: [String]
}

例如,给定的博客文章可能具有如下文档:

{
  title: 'My blog post about MongoDB',
  date: '2020-07-06T07:00:00.000+00:00',
  description: 'A blog about Mongo',
  tags: ['MongoDB', 'Javascript']
}

我正在尝试对数据库执行查询,该查询返回每个标签的映射以及该标签在集合中出现的次数的计数。因此,例如,如果我的收藏集包含三个帖子(A,B和C),则其中:

  • A.tags = ['MongoDB', 'Random']
  • B.tags = ['MongoDB', 'React']
  • C.tags = ['Nature', 'Random']

查询将返回:

[
   { 'MongoDB', 2 },
   { 'Random', 2 },
   { 'React', 1 },
   { 'Nature', 1 },
   { 'Coding', 1 },
]

有没有办法使用某种聚合管道或类似的方法?

谢谢!

1 个答案:

答案 0 :(得分:1)

是可能的

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

PS:结果格式会有所不同,但会提供您想要的正确结果