我有一个簿记条目集合,看起来像这样:

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

    最佳答案

    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 } }
        );
    

    关于有条件的Mongodb聚合框架项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15411315/

    10-11 11:22