首页 > 解决方案 > 对集合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');
});

标签: javascriptnode.jsmongodb

解决方案


与步骤无关的“逻辑”(如何处理这些值)(将值存储在其中variables并执行“某事”)。

如何(大纲)

示例 -使用指南针按大洲分组的简单国家/地区集合 (非常compass适合学习本主题)。

我们的数据(4 个国家:意大利、英国、尼日利亚、巴西及其各大洲)。

在此处输入图像描述

步骤 1/3 - 探索你的聚合

产出 3 组(欧洲(计数 2)、非洲(1)、南美洲(1))

{
  _id: {
    continent: "$continent"
  },
  count: {
  $sum: 1,
  }
}

在此处输入图像描述

步骤 2/3 - 导出代码

从 GUI 到代码

出口 在此处输入图像描述

copy paste 在此处输入图像描述

步骤 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}`);
 });

输出:

在此处输入图像描述

相关文档:


推荐阅读