如何在nodeJS和mongoDB中进行聚合

时间:2018-12-12 12:33:15

标签: node.js mongodb aggregation-framework aggregation

这是我的数据

{"data":[{"_id":"5be83f29bea83328bca27008","purpose":"charges","amount":{"rupis":"59+5+10+60+43","total":177},"date":"2018-11-11"},
{"_id":"5be843a89043152bb453b1b4","purpose":"books","amount":{"rupis":"500+600+10+300","total":1410},"date":"2018-11-11"},
{"_id":"5bf3b30a395be7142ce5cf01","purpose":"tiffin","amount":{"rupis":"20","total":20},"date":"2018-11-15"},
{"_id":"5bf3b318395be7142ce5cf02","purpose":"movie","amount":{"rupis":"200","total":200},"date":"2018-11-10"},
{"_id":"5bf3b342395be7142ce5cf03","purpose":"snacks","amount":{"rupis":"60","total":60},"date":"2018-11-20"},
{"_id":"5bf624d135cc0832ac31e6d7","purpose":"tiffin","amount":{"rupis":"20+20","total":40},"date":"2018-11-22"},
{"_id":"5bf6258c665d9a47c88437f3","purpose":"charges","amount":{"rupis":"20","total":20},"date":"2018-11-22"},
{"_id":"5c00dd328c053104a0e0eb91","purpose":"charges","amount":{"rupis":"43","total":43},"date":"2018-11-30"},
{"_id":"5c04fd3e4b08fd12f06c98ec","purpose":"charges","amount":{"rupis":"59+5","total":64},"date":"2018-12-03"},
{"_id":"5c10e844ff1a6f06fc28e627","purpose":"shopping","amount":{"rupis":"30","total":30},"date":"2018-11-11"},
{"_id":"5c10e858ff1a6f06fc28e628","purpose":"soap","amount":{"rupis":"40+40","total":80},"date":"2018-11-11"}]}

这就是我想要的输出:

{
  "charges" : 197,
  "books" : 1410,
  "tiffin" : 60,
  "snacks" : 60,
  "shopping" : 30,
  "soap" : 80
}

我尝试了以下操作,但是它引发了错误,

db.Expense.aggregate([ 
    { $match: {  
        date: {  
            $gte: "2018-11-11", 
            $lte: "2018-11-23" 
        } 
    } }, 
    { $group: { 
        purpose: "$purpose", 
        total: { $sum: "$amount.total" } 
    } } 
]);

1 个答案:

答案 0 :(得分:0)

您的组管道期望使用_id键进行分组,将$ group管道步骤重写为

{ $group: { 
    _id: "$purpose", 
    total: { $sum: "$amount.total" } 
} } 

{ $group: { 
    _id: { purpose: "$purpose" }, 
    total: { $sum: "$amount.total" } 
} }