Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating data with $set and $sum mongodb

I was trying to do update and sum up the column value.

await single_sku_db.collection("test").updateOne(
      { _id: ObjectId(id) },
      {
        $push: {
          report: {
            $each: [
              {
                name: name,
                views,
              },
            ],
            $position: 0,
          },
        },
        $set: {
          report_status: "Completed",
          total_views: { $sum: "$report.views"},
        },
      }

I cant sum the report.views like this, will get this error.

the dollar ($) prefixed field ‘’ is not valid for storage.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there anyway to do this without using aggregate?

>Solution :

One option is to replace the $set with $inc for this:

await single_sku_db.collection("test").updateOne(
      { _id: ObjectId(id) },
      {
        $push: {
          report: {
            $each: [
              {
                name: name,
                views,
              },
            ],
            $position: 0,
          },
        },
        $set: {report_status: "Completed"},
        $inc: {total_views: views},
      })

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading