在子文档中添加数字

时间:2017-04-18 12:06:37

标签: javascript mongodb mongoose

我的子文档中包含每餐的卡路里数。它们存储为包含食物的物体阵列,如下所示:

{
 "_id": ObjectId("58f5fde7eecaaf0317185fd2"),
 "user_id": ObjectId("58d2dd4c8207c28149dbc748"),
 "calories": 2051,
 "date": 20170318,
 "snacks": [
{
  "nutrients": {
    "protein": 3.9,
    "carbs": 58.3,
    "fat": 28.7
  },
  "servings": 20,
  "calories": 426,
  "name": "6 toffee terror whirls"
 }
],
"dinner": [
{
  "nutrients": {
    "protein": "4.2",
    "carbs": "5.5",
    "fat": "27.9"
  },
  "servings": 47.5,
  "calories": 580,
  "name": "Summer Recipe Pesto Sweet pepper, Rocket & Mozarella"
  }
],
 "lunch": [
{
  "nutrients": {
    "protein": 11.3,
    "carbs": 27.3,
    "fat": 8.1
  },
  "servings": 75,
  "calories": 730,
  "name": "Wood fired rostello ham, chestnut mushrooms & mascarpone 12'' pizza"
}
],
"breakfast": [
{
  "nutrients": {
    "protein": 12.6,
    "carbs": 0.1,
    "fat": "9"
  },
  "servings": "20",
  "calories": 110,
  "name": "15 eggs from caged hends - class A"
},
{
  "nutrients": {
    "protein": "31",
    "carbs": 0.1,
    "fat": "15"
  },
  "servings": "15",
  "calories": 164,
  "name": "Smoked thick cut bacon"
}
]
}

我想要做的是将单个用户添加的一天的总卡路里相加,因此将每个食物对象的卡路里量相加。我知道我需要使用$ group和$ sum的聚合方法但是我不确定如何正确使用它。任何帮助都会很感激。

我需要的是每天输入的总卡路里。 例如

20170318:2018 ,20170230:1990

等等

这是我试过的,但它目前无效:

        user_food.find({username: req.body.username},{$group:{_id:{date:{$dayOfYear: "$date"}},total:{$sum:'$calories'}}}, function (err, user) {
        //if the user exists
        if (err) {
            console.log("something went wrong: " + err);
            return res.status(500).send(err);
        } else {
            return res.status(200).send(user);
        }
    });

2 个答案:

答案 0 :(得分:0)

$reduce可以使用$add运算符进行每次用餐。

db.collection.aggregate(
    {$match:{user_id:ObjectId("58d2dd4c8207c28149dbc748")}},
    {
      $project: {
        date:1,
        calories: { $add: [ {
          $reduce: {
            input: "$breakfast",
            initialValue: 0,
            in: { $add : ["$$value", "$$this.calories"] }
          }
        }, {
          $reduce: {
            input: "$lunch",
            initialValue: 0,
            in: { $add : ["$$value", "$$this.calories"] }
          }
        },{
          $reduce: {
            input: "$snacks",
            initialValue: 0,
            in: { $add : ["$$value", "$$this.calories"] }
          }
        }, {
          $reduce: {
            input: "$dinner",
            initialValue: 0,
            in: { $add : ["$$value", "$$this.calories"] }
          }
        } ] }
      }
    }
)   

答案 1 :(得分:0)

在按日期和总卡路里之前使用$ unwind,

   db.collection.aggregate([{
      $match: {
          key: value
      }
   }, {
      $unwind: "$snacks"
   }, {
      $group: {
          _id: "$date",
          totalCalories: {
              $sum: "$calories"
          }
      }
   }])

20170318日的输出将是,

{ "_id" : 20170318, "totalCalories" : 2051 }
相关问题