Node.js Mongoose聚合、匹配、计数、组

Node.js Mongoose聚合、匹配、计数、组,node.js,mongodb,mongoose,mongodb-query,mongoose-schema,Node.js,Mongodb,Mongoose,Mongodb Query,Mongoose Schema,我正试图从我的节点API发送一个包含计数的付费和未付费客户总数列表以及数据。 在猫鼬方法中,我一直在思考如何走得更远 有人能提出实现这一目标的最佳方法吗 router.get("/", ensureAuthenticated, (req, res) => { Loan.aggregate([ { $match: { ePaidunpaid: "Unpaid" } } ]).then(function(data) {

我正试图从我的节点API发送一个包含计数的付费和未付费客户总数列表以及数据。 在猫鼬方法中,我一直在思考如何走得更远

有人能提出实现这一目标的最佳方法吗

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
根据
ePaidUnpaddy
字段对所有文档进行分组,该字段只有两个值
Paid
Unpaddy
,因此仅分别呈现两个文档

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


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

在这种情况下,请尝试此方法-

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
根据
ePaidUnpaddy
字段对所有文档进行分组,该字段只有两个值
Paid
Unpaddy
,因此仅分别呈现两个文档

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


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

请发布您期望查询结果的形状。@HimanshuSingh查看编辑请发布您期望查询结果的形状。@HimanshuSingh查看编辑