翻译或纠错本页面

$mul

Definition

$mul

2.6 新版功能.

Multiply the value of a field by a number. To specify a $mul expression, use the following prototype:

{ $mul: { field: <number> } }

The field to update must contain a numeric value.

To specify a <field> in an embedded document or in an array, use dot notation.

Behavior

Missing Field

If the field does not exist in a document, $mul creates the field and sets the value to zero of the same numeric type as the multiplier.

Atomic

$mul is an atomic operation within a single document.

Mixed Type

Multiplication with values of mixed numeric types (32-bit integer, 64-bit integer, float) may result in conversion of numeric type. For multiplication with values of mixed numeric types, the following type conversion rules apply:

  32-bit Integer 64-bit Integer Float
32-bit Integer 32-bit or 64-bit Integer 64-bit Integer Float
64-bit Integer 64-bit Integer 64-bit Integer Float
Float Float Float Float

注解

  • If the product of two 32-bit integers exceeds the maximum value for a 32-bit integer, the result is a 64-bit integer.
  • Integer operations of any type that exceed the maximum value for a 64-bit integer produce an error.

Examples

Multiply the Value of a Field

Consider a collection products with the following document:

{ _id: 1, item: "ABC", price: 10.99 }

The following db.collection.update() operation updates the document, using the $mul operator to multiply the value in the price field by 1.25:

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

The operation results in the following document, where the new value of the price field 13.7375 reflects the original value 10.99 multiplied by 1.25:

{ _id: 1, item: "ABC", price: 13.7375 }

Apply $mul Operator to a Non-existing Field

Consider a collection products with the following document:

{ _id: 2,  item: "Unknown" }

The following db.collection.update() operation updates the document, applying the $mul operator to the field price that does not exist in the document:

db.products.update(
   { _id: 2 },
   { $mul: { price: NumberLong(100) } }
)

The operation results in the following document with a price field set to value 0 of numeric type NumberLong, the same type as the multiplier:

{ "_id" : 2, "item" : "Unknown", "price" : NumberLong(0) }

Multiply Mixed Numeric Types

Consider a collection products with the following document:

{ _id: 3,  item: "XYZ", price: NumberLong(10) }

The following db.collection.update() operation uses the $mul operator to multiply the value in the price field NumberLong(10) by NumberInt(5):

db.products.update(
   { _id: 3 },
   { $mul: { price: NumberInt(5) } }
)

The operation results in the following document:

{ "_id" : 3, "item" : "XYZ", "price" : NumberLong(50) }

The value in the price field is of type NumberLong. See Multiplication Type Conversion Rules for details.

←   $inc $rename  →