Search code examples
mongodbupdatingdivide

Mongo divide the value of the field by the specified amount


I use $mul operator in update for multiplies field value

db.products.update(
   { _id: 1 },
   { $mul: { price: NumberDecimal("1.25"), qty: 2 } }
)

now how can divide field ?

Mongodb document not exist $div operator


Solution

  • From the mathematical point of view you can still use $mul to divide since there's an inverse relationship between those two operations. For instance:

    var divideBy = 2;
    var multiplyBy = 1/divideBy;
    
    db.products.update(
       { _id: 1 },
       { $mul: { price: multiplyBy } }
    )
    

    You'll get the same result as for missing $div operator