Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65864213/grouping-and-counting-occurrence-values-in-a-collection-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 db.kids.aggregate([ {$group:{_id:"$location" , count:{$sum:1}  }    }     ])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...