Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

Update all documents setting a value equal to value of an array where index taken from another value (MongoDB)

$
0
0

I am trying to execute a mongo Shell command on a 80k documents Collection in MongoDB.

Here is a sample doc:

{ 
   "weights":[ 
      { 
         "amount":100,
         "description":"grams",
         "grams":100
      },
      { 
         "amount":1,
         "description":"cup",
         "grams":258
      },
      { 
         "amount":1,
         "description":"tbsp",
         "grams":16
      },
      { 
         "amount":1,
         "description":"tsp",
         "grams":5.38
      }
   ],
   "default_units":2,
   "nutrition":{ 
      "calories":598,
      "carbs":22.31,
      "fats":51.36,
      "proteins":22.21,
   },
   "serving_calories":95,
   "serving_carbs":3,
   "serving_fats":8,
   "serving_proteins":2,
}

What I want to do is go over each Doc in the collection and update the "serving_calories" field to be as follows:

serving_calories = doc.nutrition.calories * (doc.weights[doc.default_units].grams / 100);

So executing this properly would make serving_calories = 598 * (16 / 100) = ‭95.68‬

I wasn't able to find the right commands to be able to do the array index as needed from another value. What is the right mongo command to execute?


Viewing all articles
Browse latest Browse all 138134

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>