2013-03-14 31 views
4

我有記賬條目的集合,看起來像這樣的MongoDB聚合框架項目:與條件

{ 
    _id: 5141aff1a1d24c991a000002, 
    date: 2012-02-23 00:00:00 UTC, 
    details: "sdfd", 
    value: 250, 
    clinic_id: "513e2227a1d24ceab3000001" 
} 

我想每月的信用卡和借記總數的報告。就像這樣:

[ 
    {"credit"=> -229, "debit" => 0 "month"=>1}, 
    {"credit"=> -229, "debit" => 0 "month"=>2}, 
    {"credit"=> -229, "debit" => 0 "month"=>3}, 
    {"credit"=> -229, "debit" => 0 "month"=>4}, 
    {"credit"=> -229, "debit" => 0 "month"=>5}, 
    {"credit"=> -229, "debit" => 0 "month"=>6}, 
    {"credit"=> -229, "debit" => 0 "month"=>7}, 
    {"credit"=> 0, "debit" => 300 "month"=>8}, 
    {"credit"=> 0, "debit" => 300 "month"=>9}, 
    {"credit"=> 0, "debit" => 300 "month"=>10}, 
    {"credit"=> 0, "debit" => 300 "month"=>11}, 
    {"credit"=> 0, "debit" => 300 "month"=>12} 

]

爲了做到這一點,我打算使用聚合框架。

  • 如何在$ value < = 0時將$ value賦值給credit
  • 當$ value> = 0時,如何將$ value分配給debit
  • 如何對此進行分組?

我有這樣的:

BookKeepingEntry.collection.aggregate(
    [ { "$match" => { "clinic_id" => self.clinic.id } }, 
     { "$project" => 
     {   
      "credit" => { what here? }, 
      "debit" => { What here?} 
      "month" => { "$month" => "$date" } 
     } 
     }, 
     { "$group" => {} } 
     { "$sort" => { "month" => 1 } } 
    ] 
) 
+2

看看在['$ cond'(http://docs.mongodb.org/manual/reference/aggregation/#_S_cond)投影算子。 – JohnnyHK 2013-03-14 14:23:23

+0

我曾經問過類似的問題,@JohnnyHK回答了它:) http://stackoverflow.com/questions/14102596/conditional-sum-in-mongodb請參閱下面的答案。 – 2013-03-14 14:32:06

回答

9
BookKeepingEntry.collection.aggregate(
    { $project: { 
     _id: 0, 
     credit : { $cond: [ {$lt: ['$value',0]}, '$value', 0 ] }, 
     debit : { $cond: [ {$gt: ['$value',0]}, '$value', 0 ] }, 
     month : { $month : "$date" } 
    }}, 
    { $group : {_id: {Month: "$month"} , CreditSum: {$sum: "$credit"}, DebitSum: {$sum: "$debit"}} }, 
    { $sort : { "_id.Month" : 1 } } 
    );