2014-09-03 62 views
1

我是mongo的新手,我试图从名为“transactions”的mongo db集合中获得总金额,其中“paid”为true,“creationDate”为月2014年9月,按日分组。然而有条件日期汇总的Mongo聚合

select to_char("creationDate", 'YYYY-MM') as "Month", sum(totalamount) 
from transactions 
where "creationDate" >= '2014-09-01' 
and paid is true 
group by "Month" 

,我不知道如何添加条件creationDate和蒙戈支付:

在Postgres里,我可以为写这篇文章。我阅读了有条件的聚合,但我不确定如何让它在日期和月份以及逻辑条件下工作。

的样本数据:

{ "totalamount" : 10, "creationDate" : ISODate("2014-09-01T01:00:58.909Z"), "paid" : true} 
{ "totalamount" : 30, "creationDate" : ISODate("2014-09-01T03:00:58.909Z"), "paid" : true} 
{ "totalamount" : 20, "creationDate" : ISODate("2014-09-02T01:00:58.909Z"), "paid" : true} 

这是我的尝试:

db.transactions.aggregate( 
[ 
    { 
     $group: 
      { 
       _id: { 
        day: { $dayOfMonth: "$creationDate"}, 
        month: 
         { 
          $cond: [{ $gte: [$month: "$creationDate", 9]},9,0]         
         }, 
        year: 
         { 
          $cond: [{ $gte: [$year: "$creationDate", 2014]},2014,0]         
         }, 

        }, 
       collected: { 
        $sum: { 
         $cond: [ 
          {"$paid":"true"}, "$totalamount",0] 
        } 
       } 
      } 
    } 
] 
) 

但是,我越来越"SyntaxError: Unexpected token :"

任何见解,这将是非常有益的。谢谢!

回答

0

在那里有几个问题,所以有点超出评论。大多数情况下,您并没有将几个日期操作符与{}放在一起,并在数组中生成无效的JSON。如果您更改缩进样式以便更轻松地找到格式问题,它也会有所帮助。

我还亲自宁愿坚持全面严格的JSON符号,它与其他语言解析好,更容易"lint",这是你应该看看,以避免在未来的编码语法错误:

db.transactions.aggregate([ 
    { "$group": { 
     "_id": { 
      "day": { "$dayOfMonth": "$creationDate" }, 
      "month": { 
       "$cond": [ 
        { "$gte": [ {"$month": "$creationDate"}, 9 ] }, 
        9, 
        0 
       ]         
      }, 
      "year": { 
       "$cond": [ 
        { "$gte": [ { "$year": "$creationDate" }, 2014] }, 
        2014, 
        0 
       ]         
      } 
     }, 
     "collected": { 
      "$sum": { 
       "$cond": [ 
        { "$eq": [ "$paid", "true" ] }, 
        "$totalamount", 
        0 
       ] 
      } 
     } 
    }} 
]) 

此外,在$sum末尾缺少与$eq的逻辑检查。在这种情况下,让你实际上的意思是“真”的“字符串”值,而不是true作为普通的布尔值。