MongoDB分组统计作者文章数并接入ChartJS技术求助
解决方案:MongoDB分组统计 + ChartJS 数据接入
1. MongoDB 聚合查询实现作者文档数统计
直接用MongoDB的聚合管道完成分组统计,核心是$group阶段按author字段分组,用$sum统计数量:
// 原生MongoDB驱动写法 db.posts.aggregate([ { $group: { _id: "$author", // 按author字段分组 postCount: { $sum: 1 } // 统计每组的文档数量 } }, { $sort: { postCount: -1 } } // 可选:按数量降序排序 ]) // Mongoose 模型写法 const Post = require('./models/Post'); // 假设你的模型文件路径 const authorStats = await Post.aggregate([ { $group: { _id: "$author", postCount: { $sum: 1 } } }, { $sort: { postCount: -1 } } ]);
2. Node.js 后端接口封装
用Express写一个接口,返回适配ChartJS的格式:
const express = require('express'); const router = express.Router(); const Post = require('./models/Post'); router.get('/author-stats', async (req, res) => { try { const stats = await Post.aggregate([ { $group: { _id: "$author", postCount: { $sum: 1 } } }, { $sort: { postCount: -1 } } ]); // 转换为ChartJS需要的结构:labels数组 + data数组 const chartData = { labels: stats.map(item => item._id), datasets: [{ label: '作者发布文档数量', data: stats.map(item => item.postCount), backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'], // 可选:自定义颜色 borderWidth: 1 }] }; res.json(chartData); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;
3. 前端ChartJS 数据接入
在前端页面中请求接口并渲染图表:
<!-- 引入ChartJS --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <canvas id="authorChart" width="400" height="200"></canvas> <script> // 请求后端接口获取数据 fetch('/author-stats') .then(res => res.json()) .then(chartData => { const ctx = document.getElementById('authorChart').getContext('2d'); new Chart(ctx, { type: 'bar', // 可选:bar、pie、line等图表类型 data: chartData, options: { responsive: true, scales: { y: { beginAtZero: true, title: { display: true, text: '文档数量' } }, x: { title: { display: true, text: '作者名称' } } } } }); }) .catch(err => console.error('获取数据失败:', err)); </script>
如果需要调整图表类型,只需要修改type字段(比如改成pie)即可。
内容的提问来源于stack exchange,提问作者Emre Ilgın Tamtürk
相关产品推荐
相关产品推荐

