How to calculate a field in mongodb Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to calculate a field in mongodb without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Hello i am trying to make a caculate field in mongoDB, however i get this error: MongoError: The dollar ($) prefixed field ‘$add’ in ‘$add’ is not valid for storage.

This is the code:

router.post('/char1btn', ensureAuthenticated, function(req, res) {
    const {
        MongoClient
    } = require("mongodb");
    //Replace the uri string with your MongoDB deployment's connection string.
    const uri =
        'mongodb+srv://test:test1234@databasetest.5f9jh.mongodb.net/Databasetest?retryWrites=true&w=majority';
    const client = new MongoClient(uri);
    async function run() {
        try {
            await client.connect();
            const database = client.db("Databasetest");
            const collection = database.collection("users");
            //create a filter for charactername to update
            const filter = {
                characterimg: ""
            };
            // this option instructs the method to create a document if no documents match the filter
            const options = {
                upsert: false
            };
            const updateDoc = {
                $set: {
                    health: 150,
                    attack: 3,
                    defence: 3,
                    endurance: 10,
                    characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
                },
                $set: {
                    $add: ["$power", "$attack", "$defence", {
                        $devide: ["$endurance", 3]
                    }]
                }
            }
            const result = await collection.updateOne(filter, updateDoc, options);
            console.log(
                `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
            );
        } finally {
            res.redirect('/main');
            await client.close();
        }
    }
    run().catch(console.dir);
})

Does anyone know how to fix this?

Answer

Try this one:

const updateDoc = [
   {
      $set: {
         health: 150,
         attack: 3,
         defence: 3,
         endurance: 10,
         characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
      }
   },
   {
      $set: {
         result: { $sum: ["$power", "$attack", "$defence", { $divide: ["$endurance", 3] }] }
      }
   }
];
const result = await collection.updateOne(filter, updateDoc, options);

You need two $set stages. Otherwise $sum: [...] (or $add) will use old values or fail if fields did not exist before. Also be aware that updateDoc need to be an array, see updateOne()

We are here to answer your question about How to calculate a field in mongodb - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji