我如何使用mongoose/ mongodb在单个查询中应用$ match,$ group和$ sum
我正在尝试用我对MongoDB的基本知识来find解决scheme。
我有像下面的数据
{ _id: 45556, "name": "John", "gender": "male", "lunch_preference":[ {"outlet":"KFC", "day":"monday", "spent":300}, {"outlet":"Mc", "day":"friday", "spent":250}, {"outlet":"dominos", "day":"sunday", "spent":400} ] } { _id: ab123, "name": "Peter", "gender": "male", "lunch_preference":[ {"outlet":"dominos", "day":"tuesday", "spent":150}, { "outlet":"Mc", "day":"wednesday", "spent":350}, {"outlet":"dominos", "day":"sunday", "spent":300} ] }
在这里,我正在过滤数据使用$match
我的查询过滤:
db.lunch.aggregate([{"$unwind":"$lunch_preference"}, {$match: {"lunch_preference.outlet": "dominos"}},{$match: {"lunch_preference.day": "sunday"}}])
这个查询工作正常! 现在我想计算(花费的总和)上述过滤数据的花费,所以我申请如下。
db.lunch.aggregate([{"$unwind":"$lunch_preference"}, {$match: {"lunch_preference.outlet": "dominos"}}, {$match: {"lunch_preference.day": "sunday"}}, { $group: { "_id": "$lunch_preference.outlet", totalAmount: { "$sum": "$lunch_preference.spent"}} }])
结果是:
{ "_id" : "dominos", "totalAmount" : 0 }
它显示总金额为零,帮助我!
你接近解决scheme,但你错过了以下查询将解决您的问题
db.collectionName.aggregate({ "$unwind": "$lunch_preference" }, { "$match": { "lunch_preference.outlet": "dominos", "lunch_preference.day": "sunday" } }, { "$group": { "_id": "$lunch_preference.outlet", "total": { "$sum": "$lunch_preference.spent" } } })