简体   繁体   English

如何计算每个国家使用猫鼬的重复次数?

[英]How do I count the number of duplicates for each countries using mongoose?

My following code is able to count the number of distinct cities. 我的以下代码能够计算不同城市的数量。

Get distinct countries 获取不同的国家

    IpDetails.find().distinct('city', function(error, cities) {
    console.log(`unique cities is:, ${cities}`)
})

Results 结果

unique cities is: Toronto, Waterloo

My question is, how do I get the number of times that Toronto and Waterloo appeared in my database using mongoose? 我的问题是,如何使用猫鼬获得多伦多和滑铁卢出现在数据库中的次数? Could anyone advise? 有人可以建议吗?

You should be able to do this using $aggregate with $group and $sum . 您应该可以将$ aggregate$ group$ sum一起使用 Effectively you would group each object by the the value of city and increment the count for each: 实际上,您可以按照city的值对每个对象进行分组,并为每个对象增加计数:

IpDetails.aggregate([
  { $group: { _id: "$city", count: { $sum: 1 } } }],
  function(error, groups) {
    groups.forEach(function(group) {
      console.log(`City ${group._id} appeared ${group.count} times`);
    });
  }
);

Hopefully that helps! 希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 javascript 从 json 数据中计算一个月每天的项目数 - How do I count the number of items in each day for a month from the json data using javascript 如何使用 for each 循环根据使用 JavaScript 的给定回调计算数组中的出现次数? - How do I use a for each loop to count the number of occurences in an array based on a given callback using JavaScript? 如何计算每个单词在字符串中出现的次数? - How do I count the number of times each word appears in a string? 如何使用Ramda计算数组中的重复项? - How do I count duplicates in an array with Ramda? 如何将 javascript 字符串数组减少为唯一值但保持重复数的计数? - How do I reduce a javascript string array to unique values but keep count of the number of duplicates? 如何使用文本框计算字符串中字符出现的次数? - How do I count the number of occurrences of a character in a string using textboxes? 如何使用Azure上的脚本计算表中元素的数量? - How do I count the number of elements in a table using a script on Azure? 如果有重复,我如何按日期分组并添加计数? - How do I group by date and add a count if there are duplicates? 在每次单击后重新加载页面时,如何计算按钮的单击次数? - How do I count the number of times the buttons click when the page reloads after each click? 如何获得猫鼬模型中的人口稠密儿童人数? - How do I obtain the count of populated children in a Mongoose model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM