【发布时间】:2017-04-18 21:06:05
【问题描述】:
我有包含每餐卡路里数的子文档。它们存储为包含食物的对象数组,如下所示:
{
"_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);
}
});
【问题讨论】:
标签: javascript mongodb mongoose