使用组的总百分比和查找字段进行聚合

时间:2018-05-31 05:58:26

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我试图使用Mongoose按某个字段对Mongo集合中的文档进行分组,并返回该字段的查找值以及此类文档所代表的总集合的百分比。

鉴于以下集合:

订单

{
    "_id" : ObjectId("5acdee5b80a4d21726f4fbaa"),
    "date" : ISODate("2018-04-11T11:15:40.104Z"),
    "orderType" : ObjectId("5a6cf47415621604942386aa")
},
{
    "_id" : ObjectId("5acdee5b80a4d21726f4fcbb"),
    "date" : ISODate("2018-04-12T17:43:11.317Z"),
    "orderType" : ObjectId("5a6cf47415621604942386aa")
},
{
    "_id" : ObjectId("5aba3a931cef621bd3b74ed7"),
    "date" : ISODate("2018-04-16T12:22:18.117Z"),
    "orderType" : ObjectId("5a6cf47415621604942386aa")
},
{
    "_id" : ObjectId("5acdee5b80a4d21726f4fb70"),
    "date" : ISODate("2018-04-19T08:13:01.223Z"),
    "orderType" : ObjectId("5a6cf47415621604942386bb")
}

订单类型

{
    "_id" : ObjectId("5a6cf47415621604942386aa"),
    "name" : "Order Type 1"
},
{
    "_id" : ObjectId("5a6cf47415621604942386bb"),
    "name" : "Order Type 2"
}

我希望结果数据看起来像这样:

{
    "orderType" : "Order Type 1",
    "numOrders" : 3,
    "percent" : 75
},
{
    "orderType" : "Order Type 2",
    "numOrders" : 1,
    "percent" : 25
}

我的代码如下:

  //retrieve the total number of documents in the collection 
  let total = 0;
  await models.orders.count({}).exec((err, cnt) => {
    total = cnt.valueOf();
  });

  await models.orders.aggregate(
    [
      {
        $group: {
          _id: "$orderType",
          ordersCount: { $sum: 1 }
        }
      },
      {
        $lookup: { 
          from: "OrderType", 
          localField: "orderType", 
          foreignField: "_id", 
          as: "orderType" }
      },
      {
        $project: {
          type: "$orderType.name",
          orderCount: "$totalCount",
          percent: { $multiply: [{$divide: [100, total]}, "$totalCount"]}
        }
      }
    ],(err, orders) => {
      orders.map(order => {
        //order.type is undefined here
        console.log("order type: " + order.type);
        console.log("order count: " + order.orderCount);
        console.log("order %: " + order.percent);
      })
    });

我能够使用Get percentages with MongoDB aggregate $group中给出的答案来使orderCount和百分比计算有效,但我的投影中的字段字段将以未定义的形式返回。

我对Mongoose和汇总管道都很新。我正在尝试做什么?如果是这样,我需要改变什么方法?

0 个答案:

没有答案