3

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

2 Answers2

3

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

mickl
  • 48,568
  • 9
  • 60
  • 89
3

Use update with aggregation pipeline starting from MongoDB 4.2,

Internal field as input:

db.products.update(
  { _id: 1 },
  [{ $set: { price: { $divide: ["$price", "$qty"] } } }]
)

Playground

External field as input:

var qty = 2;
db.products.update(
  { _id: 1 },
  [{ $set: { price: { $divide: ["$price", qty] } } }]
)

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59