繁体   English   中英

MongoDB 订单/销售聚合组每月总和 + 计数字段

[英]MongoDB Orders/sales aggregation group Per Month Sum Total + Count Field

谁知道按日期和总计和按来源计数对订单进行分组的更好解决方案。 当然,我可以按来源分组,然后仅获得此来源的总数,此后我可以更改结果以获得所需的结果。 但我想知道在一个简单的$group语句中是否可行。

例如。 ordersByApp = 1, ordersByWEB = 2

订单收集

{
 _id: 'XCUZO0',
 date: "2020-02-01T00:00:03.243Z"
 total: 9.99,
 source: 'APP'
},
{
 _id: 'XCUZO1',
 date: "2020-01-05T00:00:03.243Z"
 total: 9.99,
 source: 'WEB'
},
{
 _id: 'XCUZO2',
 date: "2020-01-02T00:00:03.243Z"
 total: 9.99,
 source: 'WEB'
}

我目前的聚合

Order.aggregate([
   {
     $group: {
        _id: {
           month: { $month: "$date",
           year: { $year: "$date" } 
        },
        total: {
           $sum: "$total"
        } 
     }
   }
])

当前结果

[
  {
    _id: { month: 01, year: 2020 },
    total: 19.98
  },
  {
    _id: { month: 02, year: 2020 },
    total: 9.99
  }
]

想要的结果,我怎样才能达到以下目标?

[
  {
    _id: { month: 01, year: 2020 },
    total: 19.98,
    countByApp: 1, <---
    countByWEB: 0, <---
  },
  {
    _id: { month: 02, year: 2020 },
    total: 9.99,
    countByWEB: 2, <---
    countByAPP: 0  <---
  }
]

您可以像下面这样使用$cond

Order.aggregate([
    {
        $group: {
            _id: {
                month: { $month: "$date" },
                year: { $year: "$date" } 
            },
            total: { $sum: "$total" },
            countByApp: { $sum: { $cond: [ {$eq: [ "$source", "APP" ]} , 1, 0] } },
            countByWeb: { $sum: { $cond: [ {$eq: [ "$source", "WEB" ]} , 1, 0] } },
        }
    }
])

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM