简体   繁体   中英

How to do aggregation in nodeJS and mongoDB

This is my data:

{"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"}]}

That's the output I want:

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

I have tried the following but it's throwing errors,

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

Your group pipeline is expecting an _id key to group by, re-write your $group pipeline step to

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM