【问题标题】:Mongodb mongoose query get count of documents by referenceMongodb mongoose查询通过引用获取文档数
【发布时间】:2020-10-16 22:34:39
【问题描述】:

我在 mongodb 中有 2 个集合。文章和标签。 在文章中,可以有多个标签。 以下是文章架构:

const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    tags: [{
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Tag'
    }]
}, {
    timestamps: true
});
const Article = mongoose.model('Article', articleSchema);
module.exports = Article;

以下是标签架构:

const mongoose = require('mongoose');
const tagSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true,
        unique: true
    }
}, {
    timestamps: true
});
const Tag = mongoose.model('Tag', tagSchema);
module.exports = Tag;

从这些集合中,我想展示一个简单的柱形图,它显示 一个标签有多少篇文章。 我正在尝试以如下格式获取数据:

const data = [
  { title: 'Javascript', count: 20 },
  { title: 'ReactJs', count: 12 },
  { title: 'NodeJs', count: 5 }
];

我尝试过聚合 $lookup 但无法找到解决方案。 也试过这个answer

以下我已经尝试过,但它没有给出想要的输出。

const result = await Tag.aggregate([
        {
            $lookup:
            {
                from: "articles",
                localField: "_id",
                foreignField: "tags",
                as: "articles"
            }
        }
    ])

它给出这样的输出,它根据标签返回文章数组,但我只需要文章数。

[{
    "_id": "5f6f39c64250352ec80b0e10",
    "title": "ReactJS",
    articles: [{ ... }, { ... }]
},{
    "_id": "5f6f40325716952d08a6813c",
    "title": "Javascript",
    articles: [{ ... }, { ... },{ ... }, { ... }]
}]

如果有人知道解决方案,请告诉我。谢谢。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:
    • $lookuparticles 合集
    • $project 显示必填字段并使用 $size 获取 articles 数组的总大小
    const result = await Tag.aggregate([
      {
        $lookup: {
          from: "articles",
          localField: "_id",
          foreignField: "tags",
          as: "articles"
        }
      },
      {
        $project: {
          _id: 0,
          title: 1,
          count: { $size: "$articles" }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2016-01-11
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2023-03-30
      • 2012-10-17
      • 1970-01-01
      • 2020-08-02
      • 2023-03-21
      相关资源
      最近更新 更多