mongodb(mongoose) 如何显示标签的排名

mongodb(mongoose) how to show ranking of tags

假设我有这样的架构,

Books.js

const books = new Schema({
    _user: {type: Schema.Types.ObjectId, ref: 'User'},
    title: String,
    language: String,
    description: String,   
    tags: {type: Object, ref: 'Tags'},

})

Tags.js

const tag = new Schema({
    name: String,
    description: String
})

我想显示当前存储在书 collection 中的标签的排名和总数。 例如,如果我有以下数据

数据 1

  title: momo,
    language: korean,
    description: a korean book
    tags: [{name: adventure, description: genre of fiction in which an adventure, an exciting undertaking involving risk and physical danger, forms the main storyline}, 
{name: children, description: blahblah},  {name: short, description: blahblahblah}]

数据 2

  title: tarzarn,
    language: english,
    description: english book
    tags: [{name: adventure, description: genre of fiction in which an adventure, an exciting undertaking involving risk and physical danger, forms the main storyline}, 
{name: children, description: blahblah},  {name: long, description: blahblahblah}]

**数据3 **

  title: Am I small,
    language: Korean,
    description: korean book
    tags: [{name: adventure, description: genre of fiction in which an adventure, an exciting undertaking involving risk and physical danger, forms the main storyline}, 
{name: children, description: blahblah}]

在这里我们可以看到带有adventure的标签出现了3次,children出现了2次,short 1 次和 long 1 次

因此标签的排名应该是

  1. 冒险:3
  2. Children : 2
  3. 短:1
  4. 长:1

我怎样才能通过 mongodb 查询实现这个?

您可以使用 MongoDB 聚合 管道阶段 $unwind and then $group

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

您可以找到工作示例here