Correct way to add a new field with a division between existing fields

Hi

Can some one tell me the correct way to do this:

I got this collection:

{
  "_id": {
    "$oid": "653c626b6ae0997703ddb119"
  },
  "count": 39028,
  "totalSize": 10014720
},

need to add a new field

db.collection.updateMany({}, { $set: { "avgValue": "$totalSize" / "$count"}  } )

I’m getting this result:

{
  "_id": {
    "$oid": "653c626b6ae0997703ddb119"
  },
  "count": 39028,
  "totalSize": 10014720,
  "avgSize": {
    "$numberDouble": "NaN"
  }
},

And I just need:

{
  "_id": {
    "$oid": "653c626b6ae0997703ddb119"
  },
  "count": 39028,
  "totalSize": 10014720,
  "avgSize": 256.60346418
}

Thanks

When your expression in a $set refers to field of the document you want to update you need to use
https://www.mongodb.com/docs/v5.3/tutorial/update-documents-with-aggregation-pipeline/.

In your case, you would need to do

db.collection.updateMany({}, [ { $set: { "avgValue": "$totalSize" / "$count"}  } ] )

So simply enclose the $set object into a matching pair of square brackets.