【发布时间】: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: [{ ... }, { ... },{ ... }, { ... }]
}]
如果有人知道解决方案,请告诉我。谢谢。
【问题讨论】: