5

次のような簿記エントリのコレクションがあります。

{
    _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}

]

そのために、集計フレームワークを使用する予定です。

  • credit$value <= 0 の場合に $ value を割り当てるにはどうすればよいですか?
  • debit$value >= 0 の場合に $ value を割り当てるにはどうすればよいですか?
  • これをグループ化するにはどうすればよいですか?

私はこれを持っています:

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

1 に答える 1

11
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 } }
    );
于 2013-03-14T14:31:50.820 に答える