我的用户模型类似于:
{
email: String,
name: String,
role: String,
location: {
country: String,
city: String
},
contacts: {
email: String,
phone: String
}
}
我的想法是在主页上显示以下信息:
因此,在标题中我希望有一个国家/地区列表:
每个国家/地区的城市列表:
在正文中,用户列表......
目前我的查询适用于除城市以外的所有内容。
查询是:
User.aggregate([
{
$group: {
_id: { country: '$location.country' },
users: { $push: '$$ROOT' },
cities: { $addToSet: '$location.city' },
count: { $sum: 1 }
}
}
], function(err, results) {
console.log(results);
});
};
在$sum
内加$addToSet
会很高兴,但遗憾的是它不起作用。
如何改进此代码?
答案 0 :(得分:0)
这是一个mongo查询,可以满足您的要求:
User.aggregate([
{ $group: { _id: { city: "$location.city", country: "$location.country" }, users: { $push: "$$ROOT" }, count: { $sum: 1 } } },
{ $group: { _id: "$_id.country", count: { $sum: "$count" }, cities: { $push: { city: "$_id.city", count: "$count", users: "$users" } } } }
], function(err, results) {
console.log(results);
});