Home > Blockchain >  I need to find the food that take less that 60 min to cook and prep. Time = Cook prep
I need to find the food that take less that 60 min to cook and prep. Time = Cook prep

Time:02-18

Json file

[
    {
        "_id": 1,
        "Title": "Chicken",
        "Name": "Ginger & caramel apple puddings",
        "Description": "Quintessentially British ingredients make up Frances Auger's comforting puds, impressing the judges of Britain's Best Pud",
        "Time": [
            {
                "Prep": 30
            },
            {
                "Cook": 20
            }
        ],
        "Serves": 6,
        "Nutrition": [
            "Kcal 470",
            "fat 28g",
            "saturates 17g",
            "carbs 53g",
            "sugars 39g",
            "fibre 1g",
            "protein 4g",
            "salt 1.07g"
        ],
    },
    {
        "_id": 2,
        "Title": "Vegetarian",
        "Name": "Crispy grilled feta with saucy butter beans",
        "Description": "Stuck in a food rut? Grab a can of butter beans, some feta and passata to make this super-speedy and super-tasty supper. Full of goodness, it’s healthy too ",
        "Time": [
            {
                "Prep": 30
            },
            {
                "Cook": 20
            }
        ]
    }
]

. i have been using this code but not getting the required result i am trying to sum the time that is cook and prep and need to find total time(foo prep) which take less than 60 min

db.Recipes.aggregate(["$project": {"Time": {"$sum": "$Time.cook"}}]).pretty()

CodePudding user response:

What you want to do is $sum the entire array, not just the cook time as you mentioned. You can easily achieve this with $map, like so:

db.collection.aggregate([
  {
    "$addFields": {
      "TotalTime": {
        $sum: {
          $map: {
            input: "$Time",
            in: {
              "$ifNull": [
                "$$this.Prep",
                "$$this.Cook"
              ]
            }
          }
        }
      }
    }
  },
  {
    $match: {
      TotalTime: {
        $lte: 60
      }
    }
  }
])

Mongo Playground

  • Related