2015-03-03 73 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