Julia
Julia

Reputation: 13

Use of $sum inside set - Mongodb

I have the following problem.

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.

I tried this:

  db.collection('restaurants').updateMany(
    {}, { $set: 
      { allScores: {$sum: "$grades.score"} } 
    }
  )

but it doesn't work. I get the following error:

The dollar ($) prefixed field '$sum' in 'allScores.$sum' is not valid for storage.

Why can't I use $sum inside of $set? And what can I do instead?

The database I used can be found here: https://www.w3resource.com/mongodb-exercises/

Thanks!

Julia

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"} } 
    }
  )

Upvotes: 1

Views: 1971

Answers (1)

Caconde
Caconde

Reputation: 4483

You can use aggregate() with $out to do that:

db.collection('restaurants').aggregate([
    {$addFields : {allScores : {$sum : "$grades.score"}}},
    {$out : "restaurants"}
])

What this code does:

1- Find all documents inside restaurants;
2- Add the field allScores to each document;
3- Save all documents back to the collection restaurants;

Upvotes: 1

Related Questions