【问题标题】:mongodb(mongoose) how to show ranking of tagsmongodb(mongoose)如何显示标签的排名
【发布时间】:2020-10-15 08:15:23
【问题描述】:

假设我有这样的架构,

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

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

数据 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. 儿童:2
  3. 短:1
  4. 长:1

如何通过 mongodb 查询实现这一点?

【问题讨论】:

    标签: mongodb mongoose database-design mongodb-query database-schema


    【解决方案1】:

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

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

    您可以找到工作示例here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多