使用$ reduce导致服务器上的错误

时间:2017-05-04 13:12:51

标签: mongodb

我在本地托管开发中使用了reduce功能,但是现在我已将代码部署到实时服务器,现在我遇到错误:

MongoError: exception: invalid operator '$reduce'

我用它来获取每日食物日记来计算消耗的总卡路里:

user_food.aggregate({$match:{user_id:mongoose.Types.ObjectId(req.session.user_id)}},{$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"]}}}]}}}, function (err, results) {
        //if there is an error
        if (err) {
            console.log("something went wrong: " + err);
            return res.status(500).send(err);
        } else {
            return res.status(200).send(results);
        }
    });

用户食物的文件非常简单:

{
 "_id": ObjectId("58d26c3dd60bd36f40fa0498"),
 "user_id": ObjectId("587cd30bd338b90a6c18e58f"),
 "calories": 2000,
 "date": 20170222,
 "snacks": [
  {
  "nutrients": {
    "protein": 7.5,
    "carbs": 56.5,
    "fat": 10.5
  },
  "servings": 23.8,
  "calories": 526,
  "name": "Dairy milk"
}
],
 "dinner": [ ],
 "lunch": [
{
  "nutrients": {
    "protein": 9.5,
    "carbs": 25.4,
    "fat": 17.2
  },
  "servings": 60,
  "calories": 751,
  "name": "2 pork sausages rolls"
}
 ],
 "breakfast": [
{
  "nutrients": {
    "protein": "4.8",
    "carbs": "65",
    "fat": "26"
  },
  "servings": 20.5,
  "calories": 438,
  "name": "Oreo"
}
],
"__v": 0
}

如果有人能指出我正确的方向来解决这个问题,那就非常感激。

1 个答案:

答案 0 :(得分:2)

您可以在2.6 mongo版本中尝试以下聚合。

使用$project的{​​{1}}替换所有空数组$size,然后{ calories: 0 }替换所有嵌入式数组,$ group替换$ date和$ add所有卡路里。

$unwind

有关user_food.aggregate( {$project: { date:1, breakfast :{ $cond: [{$eq: [{$size: "$breakfast"}, 0] }, [ { calories: 0 } ], "$breakfast"] }, lunch :{ $cond: [{$eq: [{$size: "$lunch"}, 0] }, [ { calories: 0 } ], "$lunch"] }, snacks :{ $cond: [{$eq: [{$size: "$snacks"}, 0] }, [ { calories: 0 } ], "$snacks"] }, dinner :{ $cond: [{$eq: [{$size: "$dinner"}, 0] }, [ { calories: 0 } ], "$dinner"] } } }, {$unwind:"$breakfast"}, {$unwind:"$lunch"}, {$unwind:"$snacks"}, {$unwind:"$dinner"}, {$group:{_id:"$date", calories:{$sum:{ $add: [ "$breakfast.calories", "$lunch.calories","$snacks.calories", "$dinner.calories"] }} }} ) 部分$unwind empty array

的更多信息