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").
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).
Output 3 groups (Europe (count 2), Africa (1), South America (1))
{
_id: {
continent: "$continent"
},
count: {
$sum: 1,
}
}
From GUI to code
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:
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.