title: Use of $sum inside set - Mongodb
body: <p>I have the following problem.</p>
  
  <p>I want to create inside my mongodb database a new field for each documentation. This field should consist as a value the sum of two other fields of the documentation.</p>
  
  <p>I tried this:</p>
  
  <pre><code>  db.collection('restaurants').updateMany(
      {}, { $set: 
        { allScores: {$sum: "$grades.score"} } 
      }
    )
  </code></pre>
  
  <p>but it doesn't work. I get the following error:</p>
  
  <p>The dollar ($) prefixed field '$sum' in 'allScores.$sum' is not valid for storage.</p>
  
  <p>Why can't I use $sum inside of $set? 
  And what can I do instead?</p>
  
  <p>The database I used can be found here: <a href="https://www.w3resource.com/mongodb-exercises/" rel="nofollow noreferrer">https://www.w3resource.com/mongodb-exercises/</a></p>
  
  <p>Thanks!</p>
  
  <p>Julia</p>
  
  <pre><code>const MongoClient = require('mongodb').MongoClient;
  ObjectID = require('mongodb').ObjectID;
  
  // Connection URL
  const url = 'mongodb://localhost:27017';
  
  // Database Name
  const dbName = 'myproject';
  
  // Use connect method to connect to the server
  MongoClient.connect(url, { useNewUrlParser: true }, function(error, client) {
  
      if(error) {
          return console.log('An error occured!')
      }
    console.log("Connected successfully to server");
  
    const db = client.db(dbName);
  
    var objectId = new ObjectID();
  
  
    db.collection('restaurants').updateMany(
      {}, { $set: 
        { allScores: {$sum: "$grades.score"} } 
      }
    )
  </code></pre>