MongoDB 统计文档(Document)的数组(Array)中的各个元素出现的次数
源数据查询输出
const result = await Post.find();
[
{"_id": "60e80e74148a45796000888c", "tags": ["前端", "Vue"], "title": "Vue 教程", "markdown": "Vue 教程"},
{"_id": "60e80ea7148a4579600088a2", "tags": ["前端", "React"], "title": "前端 React", "markdown": "前端 React 内容"},
{"_id": "60e80ede148a4579600088c1", "tags": ["前端", "React"], "title": "React 教程", "markdown": "前端 React 教程"},
{"_id": "60e80f0a148a4579600088d7", "tags": ["数据库", "MongoDB"], "title": "MongoDB 学习", "markdown": "MongoDB 学习中~"}
]
对 tags 字段解包,数组拆分
const result = await Post.aggregate([
{ $unwind: '$tags' },
// { $group: { _id: '$tags', tagCounts: { $sum: 1 } } },
// { $sort: { tagCounts: -1 } },
]);
[
{ "_id": "60e80e74148a45796000888c","tags": "前端","title": "Vue 教程","markdown": "Vue 教程"},
{ "_id": "60e80e74148a45796000888c","tags": "Vue","title": "Vue 教程","markdown": "Vue 教程"},
{ "_id": "60e80ea7148a4579600088a2","tags": "前端","title": "前端 React","markdown": "前端 React 内容"},
{ "_id": "60e80ea7148a4579600088a2","tags": "React","title": "前端 React","markdown": "前端 React 内容"},
{ "_id": "60e80ede148a4579600088c1","tags": "前端","title": "React 教程","markdown": "前端 React 教程"},
{ "_id": "60e80ede148a4579600088c1","tags": "React","title": "React 教程","markdown": "前端 React 教程"},
{ "_id": "60e80f0a148a4579600088d7","tags": "数据库","title": "MongoDB 学习","markdown": "MongoDB 学习中~"},
{ "_id": "60e80f0a148a4579600088d7","tags": "MongoDB","title": "MongoDB 学习","markdown": "MongoDB 学习中~"}
]
对 tags 数据分组计数
const result = await Post.aggregate([
{ $unwind: '$tags' },
{ $group: { _id: '$tags', tagCounts: { $sum: 1 } } },
// { $sort: { tagCounts: -1 } },
]);
[
{ "_id": "MongoDB", "tagCounts": 1 },
{ "_id": "Vue", "tagCounts": 1 },
{ "_id": "数据库", "tagCounts": 1 },
{ "_id": "前端", "tagCounts": 3 },
{ "_id": "React", "tagCounts": 2 }
]
按数量降序排列
const result = await Post.aggregate([
{ $unwind: '$tags' },
{ $group: { _id: '$tags', tagCounts: { $sum: 1 } } },
{ $sort: { tagCounts: -1 } },
]);
[
{ "_id": "前端", "tagCounts": 3 },
{ "_id": "React", "tagCounts": 2 },
{ "_id": "Vue", "tagCounts": 1 },
{ "_id": "数据库", "tagCounts": 1 },
{ "_id": "MongoDB", "tagCounts": 1 }
]
参考链接:
MongoDB统计文档(Document)的数组(Array)中的各个元素出现的次数
https://www.cnblogs.com/hapjin/p/7944404.html
本文链接 https://www.yidiankuaile.com/post/mongodb-implement-tags-cloud