2015-06-01 27 views
0

我是MongoDB的新手,但我試圖查詢是否有任何我的字段符合要求。

考慮以下幾點:

我有每個文件的格式爲一個集合:

{ 
    "nutrition" : [ 
     { 
      "name" : "Energy", 
      "unit" : "kcal", 
      "value" : 150.25, 
      "_id" : ObjectId("fdsfdslkfjsdf") 
     } 
     {---then there's more in the array---} 
    ] 
    "serving" : 4 
    "id": "Food 1" 
} 

我當前的代碼看起來是這樣的:

db.recipe.find(
    {"nutrition": {$elemMatch: {"name": "Energy", "unit": "kcal", "value": {$lt: 300}}}}, 
    {"id":1, _id:0} 
    ) 

下陣列營養,有一個名爲能源的領域,它的價值是一個數字。它檢查該值是否小於300,並輸出符合此要求的所有文檔(我只是輸出了名爲id的字段)。現在

我的問題是:

1)對於每一個文件,我有一個名爲「服務」的另一個領域,我應該找出是否「值」 /「服務」仍小於300。 (在服務的分值,看看它是否仍然不到300)

2)因爲我使用.find,我猜我不能使用$聚合運算符?

3)我一直在嘗試像$ divide + $ cond這樣的聚合運算符,但目前還沒有運氣。

4)通常在其他語言中,我只想創造一個變量=值/服務,然後運行它通過一個if語句來檢查,如果是低於300,但我不知道這MongoDB中

可能謝謝。

+0

預期產量是多少?你試圖達到什麼目標? – chridam

+0

如果您需要執行服務器端計算,則需要使用聚合框架或map-reduce。 –

+0

chridam - 我的預期輸出是陳述所有文檔的「id」,如果它們的值/服務小於300.我當前的代碼能夠輸出所有文檔的「id」,如果它們的值小於300但我不知道由於每份文件都有不同的價值和服務,因此如何通過服務來劃分價值。 – striker

回答

0

如果任何人遇到類似的問題,我想出瞭如何做到這一點。

db.database.aggregate([ 
    {$unwind: "$nutrition"}, //starts aggregation 
    {$match:{"nutrition.name": "Energy", "nutrition.unit": "kcal"}}, //breaks open the nutrition array 
    {$project: {"Calories per serving": {$divide: ["$nutrition.value", "$ingredients_servings"]}, //filters out anything not named Energy and unit is not kcal, so basically 'nutrition' array now has become a field with one data which is the calories in kcal data 
     "id": 1, _id:0}}, //show only the food id 
    {$match:{"Calories per serving": {$lt: 300}}} //filters out any documents that has their calories per serving equal to or greater than 300 
    ]} 

因此,基本上,你打開陣列並篩選出你不想文檔中的任何子字段,然後使用項目,任何你的數學評價,需要做一起顯示。然後你過濾出你的任何情況,對我而言,我不希望看到每份食物的卡路里超過300.