【发布时间】:2015-03-06 09:24:33
【问题描述】:
我希望从我的用户模型中检索如下所示的几个信息:
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
created_at: Date,
updated_at: Date,
genre : { type: String, enum: ['Teacher', 'Student', 'Guest'] },
role : { type: String, enum: ['user', 'admin'], default: 'user' },
active : { type: Boolean, default: false },
profile: {
name : { type: String, default: '' },
headline : { type: String, default: '' },
description : { type: String, default: '' },
gender : { type: String, default: '' },
ethnicity : { type: String, default: '' },
age : { type: String, default: '' }
},
contacts : {
email : { type: String, default: '' },
phone : { type: String, default: '' },
website : { type: String, default: '' }
},
location : {
formattedAddress : { type: String, default: '' },
country : { type: String, default: '' },
countryCode : { type: String, default: '' },
state : { type: String, default: '' },
city : { type: String, default: '' },
postcode : { type: String, default: '' },
lat : { type: String, default: '' },
lng : { type: String, default: '' }
}
});
在主页中,我有一个位置过滤器,您可以在其中浏览来自国家或城市的用户。
所有字段还包含其中的用户数量:
United Kingdom
All Cities (300)
London (150)
Liverpool (80)
Manchester (70)
France
All Cities (50)
Paris (30)
Lille (20)
Nederland
All Cities (10)
Amsterdam (10)
Etc...
这在主页中,然后我也有学生和教师页面,我希望只知道这些国家和城市有多少教师......
我要做的是创建一个对 MongoDB 的查询,以通过单个查询检索所有这些信息。
目前查询如下所示:
User.aggregate([
{
$group: {
_id: { city: '$location.city', country: '$location.country', genre: '$genre' },
count: { $sum: 1 }
}
},
{
$group: {
_id: '$_id.country',
count: { $sum: '$count' },
cities: {
$push: {
city: '$_id.city',
count: '$count'
}
},
genres: {
$push: {
genre: '$_id.genre',
count: '$count'
}
}
}
}
], function(err, results) {
if (err) return next();
res.json({
res: results
});
});
问题是我不知道如何获取我需要的所有信息。
- 我不知道如何获取每个国家/地区的总用户长度。
- 我有每个国家/地区的用户长度。
- 我有每个城市的用户长度。
- 我不知道如何获得相同的内容,但要针对特定类型。
是否可以在 Mongo 中通过一次查询获得所有这些信息?
否则:
像这样用 2、3 个不同的请求向 Mongo 创建几个承诺:
getSomething
.then(getSomethingElse)
.then(getSomethingElseAgain)
.done
我确信每次指定数据时存储会更容易,但是:当数据库中有超过 5000 / 10000 个用户时,这对性能有好处吗?
抱歉,我仍在学习中,我认为这些内容对于了解 MongoDB 性能/优化至关重要。
谢谢
【问题讨论】:
标签: javascript node.js mongodb mongoose aggregation-framework