[英]mongodb aggregate with find features
I have a model similar to this one: 我有一个与此模型类似的模型:
{
email: String,
name: String,
role: String,
location: {
country: String,
city: String
},
contacts: {
email: String,
phone: String
}
}
I need to show in my view the entire users information but I wish to include also how many users from a country there are. 我需要在视图中显示所有用户信息,但我也想包括一个国家/地区的用户数。
Using aggregate
I don't know how to get the full user over the groups I create. 使用
aggregate
我不知道如何在我创建的组上获得正式用户。
So at the moment what I'm doing is this: 所以目前我正在做的是:
User.find({}, function(err, users) {
User.aggregate([
{ $group: { _id: { country: '$location.country' }, count: { $sum: 1 }}}
], function(err, results) {
res.render('home', {
users: users,
countries: results
});
});
});
As you can see I'm using Find and then aggregate to get both the information I need... but I'm pretty sure there is a way to get it using only aggregate
but I can not find how to do that... 如您所见,我正在使用“查找”,然后使用汇总来获取我需要的信息...但是我很确定有一种方法可以仅使用
aggregate
来获取信息,但我找不到方法...
If you need to accumulate the entire user information for each group, then you need to use the $push operator for accumulation and the $$ROOT system variable to access the entire user info. 如果需要累积每个组的全部用户信息,则需要使用$ push运算符进行累积,并使用$$ ROOT系统变量来访问整个用户信息。
User.aggregate([
{$group:{"_id":{"country":"$location.country"},
"users":{$push:"$$ROOT"},
"count":{$sum:1}}}
],callback)
In case you would want to accumulate only specific fields of the user information document, you could just push the required fields like: 如果您只想累积用户信息文档的特定字段,则可以按如下所示推送必填字段:
User.aggregate([
{$group:{"_id":{"country":"$location.country"},
"users":{$push:{"email":"$email","name":"$name"}},
"count":{$sum:1}}}
],callback)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.