【发布时间】:2015-01-07 23:30:06
【问题描述】:
我仍然是 MongoDB 的初学者,我正在疯狂地用它创建一个复杂的(对我而言)查询。
所以,我的模型是:
{
email: String,
name: String,
orientation: String,
location: {
country: String,
city: String
},
contacts: {
phone: String,
email: String,
website: String
}
}
现在我创建了一个这样的查询:
User.aggregate([
{
$group: {
_id: { city: '$location.city', country: '$location.country', orientation: '$orientation' },
count: { $sum: 1 }
}
},
{
$group: {
_id: '$_id.country',
count: { $sum: '$count' },
cities: {
$push: {
city: '$_id.city',
count: '$count'
}
},
orientations: {
$push: {
orientation: '$_id.orientation',
count: '$count'
}
}
}
}
], function(err, results) {
if (err) return next();
console.log(JSON.stringify(results));
});
不幸的是,我收到了不错的数据,但只是部分数据。
我希望拥有一张唱片:
- 用户总数(我没有)
- 每个国家/地区的用户总数(我有)
- 每个城市的总用户数(我有)
- 每个方向的用户总数(我没有,我有每个城市每个方向的用户总数)
- 每个城市每个方向的用户总数(我有)
目前它返回:
[{
"_id": "France",
"count": 1,
"cities": [{
"city": "Maël-Carhaix",
"count": 1
}],
"orientations": [{
"orientation": "a",
"count": 1
}]
}, {
"_id": "United Kingdom",
"count": 4,
"cities": [{
"city": "Bagshot",
"count": 1
}, {
"city": "London",
"count": 3
}],
"orientations": [{
"orientation": "a",
"count": 1
}, {
"orientation": "a",
"count": 3
}]
}]
这是我想要的:
"totalUsers": 5,
"countries: [{
"_id": "France",
"count": 1,
"cities": [{
"city": "Maël-Carhaix",
"count": 1
}],
"orientations": [{
"orientation": "a",
"count": 1
}]
}, {
"_id": "United Kingdom",
"count": 4,
"cities": [{
"city": "Bagshot",
"count": 1
}, {
"city": "London",
"count": 3
}],
"orientations": [{
"orientation": "a",
"count": 4
},
{
"orientation": "b" // if exist...
"count: // n...
}]
}]
我认为这个查询已经更改了数百次,但我在 60% 的歌剧中。
【问题讨论】:
-
建议。您的问题中的方法略有错误,因此是解决问题的好方法。 1. 列出示例文件(只是几个) 2. 展示你想要的结果 3. (因为我们喜欢努力)展示你尝试过的东西。没有比提供示例和努力更简单的方式来解释您想要得到的东西了。
-
我认为您需要查看和了解我所做的和我需要的一切。
-
如果这是真的那我为什么要问?您真正展示的只是“您尝试过的”。架构无关紧要,显示数据。这在 MongoDB 和 mongoose 或 spring 数据或任何与要解决的问题在很大程度上无关的东西。点也不是对结果的真正解释。添加原始数据和所需结果的数据。那么就清楚了。
-
好吧,我现在添加了它返回的内容。如您所见,用户总数没有任何价值(该日志后面应该是 5 个),并且每个方向(目前都是“a”)没有应该是 5、1 在法国和 4 的用户总数在英国。
-
我刚刚改进了结果的格式。
标签: javascript node.js mongodb mongodb-query