我如何使用 mongoose/mongodb 在单个查询中应用 $match、$group 和 $sum

how do i apply $match, $group and $sum in single query using mongoose/mongodb

我正在尝试根据我对 MongoDB 的基本知识找到解决方案。

我有如下数据

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

显示总金额为零,帮帮我!

您接近解决方案,但您错过了以下查询,因此下面的查询将解决您的问题

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