MongoDB唯一值按sum排序

时间:2018-01-26 19:53:23

标签: mongodb

我的收藏如下:

{"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "13001"}
{"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "8002"}
{"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "5001"}
{"orderID" : "89765", "region" : "CA", "customerID" : "54157526", "productID" : "7412"}
{"orderID" : "89765", "region" : "CA", "customerID" : "54157526", "productID" : "5198"}
{"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "6851"}
{"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "7412"}
{"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "6987"}
{"orderID" : "21794", "region" : "NY", "customerID" : "78125522", "productID" : "13001"}

我需要计算在特定区域中按customerID分组的唯一订单ID。 到目前为止,我已尝试过以下内容:

db.collection.aggregate( [
   { $group:
      {
        _id: { region: "$region", customer:"$customerID"}
      }
   },
   { $match: { region: "KA" } },
   {$group: {_id:1, count: {$sum : 1 }}}
] );

但它返回一个空结果。

1 个答案:

答案 0 :(得分:0)

您应该在汇总开始时执行match,以确保您只使用该区域的结果

您还应该将$group更改为customerorder,因为匹配已经整理出来自所需区域的内容

然后,您应该使用group使用{$sum:1}计算唯一订单ID的数量,您可以阅读有关其工作原理的here

db.collection.aggregate( [
  { $match: { region: "KA" } },
  { $group:
    {
      _id: { order: "$orderID", customer:"$customerID"}
    }
  },
  {$group: {_id:"$_id.customerID", count: {$sum : 1 }}
]);