【问题标题】:Mongoose aggregate, Match, Count, GroupMongoose 聚合、匹配、计数、组
【发布时间】:2018-09-17 12:21:01
【问题描述】:

我正在尝试从我的节点 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
  },
]

【问题讨论】:

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

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


【解决方案1】:

那么,试试这个 -

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 的第一阶段根据ePaidunpaidfield 对所有文档进行分组,其中只有两个值Paid 或Unpaid,因此分别只呈现两个文档。

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

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

【讨论】:

    猜你喜欢
    • 2016-10-14
    • 2019-04-28
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多