javascript - 对集合MongoDB中的出现值进行分组和计数?
问题描述
希望你一切都好。我正在尝试从我的收藏中制作一个图表,但我遇到了一个问题。如何对位置进行分组,然后计算集合中的位置数量?所以对于下面的示例,我有 5 个孩子,我想知道他们所有的位置以及有多少孩子共享相同的位置,(A = 2、B = 2 和 C = 1)这样我可以绘制位置与数量的关系那个位置的孩子。总而言之,那里有哪些地点以及每个地点有多少孩子。
"name": "Tom",
"location": "A'
"name": "Sarah",
"location": "B'
"name": "Jane",
"location": "C'
"name": "HIllary",
"location": "A'
"name": "Mat",
"location": "B'
编辑这里是我的代码
router.get('/contact', function (req, res) {
const locations = Kids.aggregate([
{
$group: {
_id: {
continent: "$locations",
},
count: {
$sum: 1,
},
},
}
])
locations.forEach(function(item) {
console.log(`${item._id.province} num of kids is: ${item.count}`);
});
res.render('contact');
});
解决方案
与步骤无关的“逻辑”(如何处理这些值)(将值存储在其中variables
并执行“某事”)。
如何(大纲)
示例 -使用指南针按大洲分组的简单国家/地区集合
(非常compass
适合学习本主题)。
我们的数据(4 个国家:意大利、英国、尼日利亚、巴西及其各大洲)。
步骤 1/3 - 探索你的聚合
产出 3 组(欧洲(计数 2)、非洲(1)、南美洲(1))
{
_id: {
continent: "$continent"
},
count: {
$sum: 1,
}
}
步骤 2/3 - 导出代码
从 GUI 到代码
步骤 3/3 - aggregate() 方法和 cursoer.forEach()
相关代码(假设您使用节点连接指南连接一个 MongoDB 实例)
const aggregate_cursor = db.collection("test_listing").aggregate([
{
$group: {
_id: {
continent: "$continent",
},
count: {
$sum: 1,
},
},
}
])
并循环抛出光标:
aggregate_cursor .forEach(function(item) {
console.log(`${item._id.continent} num of countries is: ${item.count}`);
});
输出:
相关文档:
推荐阅读
- azure - GET 请求有效,POST 请求无效(Microsoft Azure South Central US)
- java - 如何在 Lucene 7.4 中索引短字段
- selenium-webdriver - 在自动化测试中打开浏览器的页面对象模型中的标准做法是什么?
- javascript - 带有异步调用的 ES6 循环
- javascript - Sequelizejs 通过两个字段“包含”
- excel - PowerQuery 合并表的结果不是默认顺序
- c# - 对二维数组列表进行排序
- visual-c++ - 编译入门 Visual C++ 项目时 Visual Studio 2017 中的 MSB4062
- php - Laravel 在哪里
- python - ImportError: 使用 pip 版本 18.0、ubuntu 18.04 运行 pip 时无法导入名称 main