node.js - Mongoose 聚合、匹配、计数、分组

标签 node.js mongodb mongoose mongodb-query mongoose-schema

我正在尝试从我的 Node API 发送一份已付费和未付费客户总数的列表,其中包含计数以及数据。 在 Mongoose 方法中,我一直在思考如何走得更远。

有人可以建议实现这一目标的最佳方法吗?

router.get("/", ensureAuthenticated, (req, res) => {
   Loan.aggregate([
     {
       $match: {
         ePaidunpaid: "Unpaid"
      }
     }
   ]).then(function(data) {
     console.log(data);
     res.render("dashboard", { admin: req.user.eUserType, user: req.user,data:data });
   });
});

贷款模式:

const Loan = new Schema({
  sName: { type: String },
  sPurpose: [String],
  sBankName: String,
  sBranchName: [String],
  nTotalFees: { type: Number },
  ePaidunpaid: { type: String ,default:'Unpaid'},
  sCashOrCheque: { type: String },
});

结果: 用户的详细信息以及付费和未付费客户的数量

[
  Paid:{
    // Paid users
},

  Unpaid:{
    // Unpaid Users
  },
]

最佳答案

那么,在这种情况下,试试这个 -

Loan.aggregate([
  {
    $group: {
      _id: "$ePaidunpaid",
      data: { $push: "$$ROOT" },
      count: { $sum: 1 }
    }
  }
]);

输出会是这样的 -

{
  "_id": "Paid",
  "data": [
    // All the documents having ePaidunpaid = Paid
    { _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields },
    { _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields }
  ],
  count: 2
},
{
  "_id": "Unpaid",
  "data": [
    // All the documents of having ePaidunpaid = Unpaid
    { _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields },
    { _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields }
  ],
  count: 2
},

说明

管道的第一阶段$group根据ePaidunpaid字段对所有文档进行分组,该字段只有两个值PaidUnpaid,从而分别渲染两个文档。

下一步是积累原始数据(文档)并分组在一起。这是通过在数据字段上使用 $push 累加器,推送 $$ROOT 来实现的,它有效地引用了管道阶段当前正在处理的文档。

由于您需要计算所有付费和未付费用户的数量,因此需要使用 $sum 累加器来计算每个组中的所有项目。

关于node.js - Mongoose 聚合、匹配、计数、分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710285/

相关文章:

node.js - Sequelize @6.3.4 无法连接到 docker -> postgres

node.js - RUN npm install 上的 Dockerfile 构建错误

spring - 使用 Spring Data MongoDB 查询纯 BSON

node.js - 单元测试: How to mock mongoose code when using populate?

javascript - 使用连接角色的 Node.js 角色授权

javascript - 在 js/node.js 中检查一行是否只包含空格和\n

node.js - 使用 NODEJS 保存到 Mongodb 后如何获得响应

ruby - 无法使用种子本地主机 :27017 连接到副本集

node.js - 匹配 Mongoose 中的两个不同字段,聚合?

node.js - Express.js 和 Mongoose : access Object attribute name by the request parameter