Mongo 将字段的值除以指定的数量

Mongo divide the value of the field by the specified amount

我在更新中使用 $mul 运算符来乘以字段值

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

现在怎么分田?

Mongodb document 不存在 $div 运算符

从数学的角度来看,您仍然可以使用 $mul 来除法,因为这两个运算之间存在反比关系。例如:

var divideBy = 2;
var multiplyBy = 1/divideBy;

db.products.update(
   { _id: 1 },
   { $mul: { price: multiplyBy } }
)

你会得到与缺少 $div 运算符相同的结果

从MongoDB 4.2开始使用update with aggregation pipeline

作为输入的内部字段:

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

Playground

外部字段作为输入:

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

Playground