Error in use of MongoDB $sum

Hi Guys,
I am a beginner, trying to make some progress, trying to calculate a new value based on existing values. Code is below. Any suggestions? Sorry if silly and simple…

client = MongoClient(“mongodb://localhost:27017/”)
database = client[“SG1local”]
collection = database[“profiles_key”]

database.collection.updateMany(
[
{
{
total_cert_score:
{
{ “$sum”: [ “$cert_1_score”, “$cert_2_score” ]}
}
}
}
]
)

Please post code as preformatted text like this:

```
def foo():
      print('I am foo')
```

It seems that your question is about MongoDB and not python?
You may find a MongoDB user here to help you, but you might need to ask on a MongoDB forum.

Suggestions for what, exactly? Are you trying to figure out how to do something? If so, exactly what should happen when the code runs? Or are you trying to fix a problem with the code you have so far? If so, what happens when you try that code, and how is that different from what you wanted it to do?

Thanks Karl,
I’m trying to sum up two fields in a collection for every document, and place the result in a third field.

I’m getting a syntax error, pointing to the $sum operator.

We cannot see your screen… Post the error here for us to look at please as pre-formatted text.

1 Like
# Requires pymongo 3.6.0+
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
database = client["SG1local"]
collection = database["profiles_key"]

collection.database.aggregate (([total_cert_score: {$sum( {['$cert_ai_score','$cert_ml_score']})}]))

query = {}

cursor = collection.find(query)
try:
    for doc in cursor:
        print(doc)
finally:
    client.close()

Thanks!

Thanks for the code, but where is the ourput with the error messages?