2014-09-03 98 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作爲普通的布爾值。