[英]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.