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

时间:2015-03-03 12:48:16

标签: node.js mongodb mongoose aggregation-framework

我正在尝试使用我对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 }

它显示总量为零,帮助我!

1 个答案:

答案 0 :(得分:1)

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

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