【问题标题】:I'd like to count the documents with the matching "name" property AND group them by "name" at the same time我想计算具有匹配“名称”属性的文档并同时按“名称”对它们进行分组
【发布时间】:2015-06-22 08:38:38
【问题描述】:

假设我有一个User 收藏:

schema = mongoose.Schema({
  firstName: {
    type: String,
    required: true
  },
  ...
  ...
});
module.exports = mongoose.model("User", schema);

我想编写一个 mongoose 查询来计算有多少用户叫 Mike、Andy、Jerry... 换句话说,我想按相同的名称对他们进行 GROUP 并计算所有组。 到目前为止,我想出的唯一想法是做最简单的find()select("username")lean(),然后使用lodash 或下划线在exec() 函数中过滤结果。

但我想知道是否可以仅使用猫鼬获得此结果。

【问题讨论】:

    标签: node.js mongoose group-by


    【解决方案1】:

    您可以使用 aggregate$group 管道阶段来执行此操作:

    User.aggregate(
        {$group: {_id: '$firstName', count: {$sum: 1}}},
        function(err, result) {...}
    );
    

    【讨论】:

      【解决方案2】:

      如果您希望 mongodb 在内部处理查询,您可以使用 aggregation framework

      在 mongodb 中是这样的:

      db.users.aggregate(
        [{
          $group: {
            _id: '$firstName', // similar to SQL group by, a field value for '_id' will be returned with the firstName values
            count: {$sum: 1} // creates a field value 'count' that will store the value
          }
        }]
      );
      

      在猫鼬中使用aggregate pipeline 将是:

      Users.aggregate()
        .group({ _id: '$firstName', count: { $sum: 1 }})
        .exec(function (err, res) {
          if (err) { return console.log(err); }
          console.log(res);
      });
      

      如果需要,您可以使用投影将 _id 的字段名称修改为 firstName

      【讨论】:

      • 这个答案比约翰尼的要详细一点,所以我会用它。谢谢。
      猜你喜欢
      • 2022-06-23
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 2018-12-26
      • 2018-02-16
      • 1970-01-01
      相关资源
      最近更新 更多