简体   繁体   中英

grouping and counting occurrence values in a collection MongoDB?

hope you are well. I am trying to make a graph from my collection but I've run into an issue. How can I group the locations and then count the number of locations in the collection? so for the example below I have 5 kids, I want to know all their locations and how many kids share the same locations, (A = 2, B = 2, and C = 1) that way I can plot Location vs the number of kids in that location. So to summarize, what locations are there and how many kids in each location.

"name": "Tom",
 "location": "A'
 
 "name": "Sarah",
 "location": "B'
 
 "name": "Jane",
 "location": "C'
 
 "name": "HIllary",
 "location": "A'
 
 "name": "Mat",
 "location": "B'

Edit here is my code

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');
});

 db.kids.aggregate([ {$group:{_id:"$location" , count:{$sum:1}  }    }     ])

"The logic" (What to do with the values) not related to the steps (Store the values in variables and do "something").

HOW TO (OUTLINE)

Example - Simple countries collection group by continents using compass (Great to use compass to learn this topic).

Our data (4 countries: Italy, England, Nigeria, Brazil, and their continents).

在此处输入图像描述

Step 1/3 - explore your aggregate

Output 3 groups (Europe (count 2), Africa (1), South America (1))

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

在此处输入图像描述

Step 2/3 - export code

From GUI to code

export在此处输入图像描述

copy paste在此处输入图像描述

Step 3/3 - aggregate() method & cursoer.forEach()

The related code (Assuming you connect a MongoDB instance using node Connection Guide )

const aggregate_cursor  = db.collection("test_listing").aggregate([
    {
      $group: {
        _id: {
          continent: "$continent",
        },
        count: {
          $sum: 1,
        },
      },
    }
])

And loop throw the cursor:

  aggregate_cursor .forEach(function(item) {
    console.log(`${item._id.continent} num of countries is: ${item.count}`);
 });

Output:

在此处输入图像描述

Related docs:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM