1
我有很多賬號,每個賬號都有一名員工。我想找到每個員工的賬戶數量。我如何使用貓鼬聚合(mongodb)來完成這項任務。我熟悉貓鼬的其他功能,並能用以下代碼實現:如何在貓鼬中進行彙總和分組
exports.accountsOfEachEmployee = function(req, res) {
Account.find({active:true}).exec(function(err, accounts){
if (err || !accounts) res.status(400).send({
message: 'could not retrieve accounts from database'
});
var accountsOfEachEmployee = {};
for (var i = 0; i < accounts.length; i++) {
if(accountsOfEachEmployee[order[i].employee]) {
accountsOfEachEmployee[order[i].employee] = 1;
} else {
accountsOfEachEmployee[order[i].employee]++;
}
}
res.json(accountsOfEachEmployee);
});
};
正在使用聚合更快嗎?分組和聚合如何在貓鼬中工作(mongodb)。以下是我的賬戶模式
var AccountSchema = new Schema({
active: {
type : Boolean,
default: false
},
employee: {
type: Schema.ObjectId,
ref: 'Employee'
},
});