[英]mongodb aggregate with find features
我有一個與此模型類似的模型:
{
email: String,
name: String,
role: String,
location: {
country: String,
city: String
},
contacts: {
email: String,
phone: String
}
}
我需要在視圖中顯示所有用戶信息,但我也想包括一個國家/地區的用戶數。
使用aggregate
我不知道如何在我創建的組上獲得正式用戶。
所以目前我正在做的是:
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
});
});
});
如您所見,我正在使用“查找”,然后使用匯總來獲取我需要的信息...但是我很確定有一種方法可以僅使用aggregate
來獲取信息,但我找不到方法...
如果需要累積每個組的全部用戶信息,則需要使用$ push運算符進行累積,並使用$$ ROOT系統變量來訪問整個用戶信息。
User.aggregate([
{$group:{"_id":{"country":"$location.country"},
"users":{$push:"$$ROOT"},
"count":{$sum:1}}}
],callback)
如果您只想累積用戶信息文檔的特定字段,則可以按如下所示推送必填字段:
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.