【问题标题】:How to aggregate and group in mongoose如何在猫鼬中聚合和分组
【发布时间】:2015-03-04 11:04:12
【问题描述】:

我有很多帐户,每个帐户都分配了一名员工。我想找到每个员工的帐户数。我如何使用 mongoose(mongodb) 的聚合来完成这项任务。我熟悉mongoose的其他功能,可以用下面的代码实现

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);
  }); 
};

使用聚合更快吗?分组和聚合如何在 mongoose(mongodb) 中工作。以下是我的帐户架构

var AccountSchema = new Schema({
  active: {
    type : Boolean, 
    default: false
  },
  employee: {
    type: Schema.ObjectId,
    ref: 'Employee'
  },
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    聚合比 map reduce 更快地在 mongodb 中获取简单查询的结果。我能够用结果完成上述查询,然后对 mongodb 进行分组计数。以下是我后来使用的查询

    Order.aggregate({$match: {active: true }}, 
      {$group: {_id:'$employee', numberOfOrders: {$sum:1}}}, function(err, orders) {
        res.json(orders);
    });
    

    查询分两部分执行。第一部分是获取所有活动的结果,然后根据员工的值对它们进行分组,同时获取一个新字段 numberofOrders,这是我们根据员工分组时形成的每个组中的文档数。

    【讨论】:

    • 看起来在 Mongoose 5.x 中它需要一个数组。在我将聚合对象包装在 [] 中之后,您的回答对我有用。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2021-05-30
    • 2018-08-22
    • 2015-05-19
    • 2015-09-15
    • 2015-02-27
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多