我仍然是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%。
答案 0 :(得分:0)
对于总用户,您可以这样做:
db.collection.distinct("email").length
对于每个方向的总用户,您可以这样做(假设您的模型中的计数是唯一用户的数量):
db.collection.group({
key: {"orientations.orientation": 1 },
reduce: function(cur, result) { result.count += cur.count },
initial: { count: 0 }
})
将来,正如Niel已经提到的那样,提供完整模型(即使您输入虚假数据)也是最好的,这样我们就可以帮助您并撰写真正有意义的答案。