Mongodb mongoose查询通过引用获取文档计数

Mongodb mongoose查询通过引用获取文档计数,mongodb,mongoose,Mongodb,Mongoose,我在mongodb有两个收藏。物品和标签。 在文章中,可以有多个标记。 以下是文章模式: const mongoose = require('mongoose'); const articleSchema = new mongoose.Schema({ title: { type: String, required: true, trim: true }, tags: [{ type: mongoose.Sc

我在mongodb有两个收藏。物品和标签。 在文章中,可以有多个标记。 以下是文章模式:

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,但找不到解决方案。 我也试过这个

下面我已经尝试过了,但是没有给出期望的输出

const result = await Tag.aggregate([
        {
            $lookup:
            {
                from: "articles",
                localField: "_id",
                foreignField: "tags",
                as: "articles"
            }
        }
    ])
它给出这样的输出,它根据标记返回articles数组,但我只需要文章数

[{
    "_id": "5f6f39c64250352ec80b0e10",
    "title": "ReactJS",
    articles: [{ ... }, { ... }]
},{
    "_id": "5f6f40325716952d08a6813c",
    "title": "Javascript",
    articles: [{ ... }, { ... },{ ... }, { ... }]
}]
如果有人知道解决方案,请让我知道。谢谢。

  • $lookup
    文章
    收藏
  • $project
    显示必填字段,并使用
    $size

  • $lookup
    文章
    收藏
  • $project
    显示必填字段,并使用
    $size

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