我的用户模型非常简单:
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
contacts : {
email : { type: String, default: '' },
phone : { type: String, default: '' },
website : { type: String, default: '' }
},
location : {
country : { type: String, default: '' },
state : { type: String, default: '' },
city : { type: String, default: '' },
postcode : { type: String, default: '' },
lat : { type: String, default: '' },
lng : { type: String, default: '' }
}
});
所有我需要做的工作正常但现在我希望有一个侧边栏,显示该地区的用户数量的国家和城市列表,即:
London (134 users)
Liverpool (98 users)
Oxford (14 users)
etc...
在主页中,我有一个简单的查询,可以获取所有用户,但我如何动态获取这些信息?
似乎我应该有一个单独的位置模型......但是我确定有一种方法可以在不创建另一个模型的情况下实现它......是不是?
我希望你能提供帮助。
答案 0 :(得分:1)
您可以使用MongoDB的aggregation framework提供如下摘要结果:
User.aggregate([
// Group all docs by country & city and get a count of each combination
{$group: {
_id: {
country: '$location.country',
city: '$location.city'
},
count: {$sum: 1}
}}
], function(err, results) { ... });