How to calculate a field

Hello everyone,

I am trying to make a calculate field but for some reason i cant get it to work:

$set: {
   health: 150,
   attack: 3,
   defence: 3,
   endurance: 10,
   power: attack +  defence + endurance / 3,
}

The power field wont be able to make the calculation… how do i fix this?

Hi @JasoO

First its easy to calculate it on application side as you know all values.
However, aggregation pipeline update can help:

[{$set: {
   health: 150,
   attack: 3,
   defence: 3,
   endurance: 10}, 
  { $set: { $add : [ "$power", "$attack" ,"$defence" , { $devide :  ["$endurance", 3]}]}}]

Thanks,
Pavel

Thank you for the answer, i am trying to do it like this:

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 {

localStorage.firstTime = "No"

res.redirect('/main'); 

await client.close();

}

}

run().catch(console.dir); 

})

But it gives me this error:

MongoError: The dollar ($) prefixed field ‘$add’ in ‘$add’ is not valid for storage.

@JasoO,

This is not an update document its a pipeline array.

You must define it like this and have a server of 4.2+

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]}]} }]

Thanks
Pavel

Hello Pavel,

The outcome of this turns to 9, but it should be: power = attack+ defence + endurance / 3 = 5,33.

Can you tell me what is going wrong here?

Hi @JasoO,

I don’t know what is value of power?

Thanks
Pavel

@Pavel_Duchovny The value of the power will be 0 at first, but then after it will do the calculation and it should be 5,33

You already have all the values, can’t you simply do:

$set: {
   health: 150,
   attack: 3,
   defence: 3,
   endurance: 10,
   characterimg: “https://i.ibb.co/MPg2SMp/Apocaliptic1.png”,
   power: 3 + 3 + 10/3,
}

in your client code. That’s much simpler than trying to have the server do the calculation.

I agree with @steevej.

But aside of that in math 3+ 3 + 10/3 is ~9.

How did you get to 5.33?

Thanks

Oh lol i am sorry it looks like i made a typo on my calculator :L Forget that i ever asked this.

Thats interesting, i tought that you could only connect to mongodb with the server. So i only have to add this line somewhere in the code? Or do i have to connect to it the same way as the server would?