2015-06-01 29 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.