2015-03-03 74 views
1

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

你接近的解决方案,但是你错过以下所以下面的查询将解决您的问题

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

它显示同样的结果,正如我以前得到。 {“_id”:“dominos”,“total”:0} – learner 2015-03-03 13:14:21

+1

@SettiMahesh它很困难,因为根据上面给出的文档,查询显示结果以及查询也显示正确的结果。 – Yogesh 2015-03-03 13:22:40

+0

问题已解决,我将花费的模式定义为字符串。我现在改变了。它工作正常 – learner 2015-03-03 13:27:35