Reputation: 3476
I have a user model very simple like this:
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: '' }
}
});
All I need to do works fine but now I wish to have a sidebar that show a list of Countries and Cities with number of Users in that place, ie:
London (134 users)
Liverpool (98 users)
Oxford (14 users)
etc...
In Homepage I have the simple query that get all users but how can I get these information dynamically?
It seems like I should have a separate model for locations... but I'm sure there is a way to implement this without create another model... is it right?
I hope you can help.
Upvotes: 0
Views: 304
Reputation: 312045
You can use MongoDB's aggregation framework to provide summary results like this:
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) { ... });
Upvotes: 1