Open In App

MongoDB – $mul Operator

MongoDB $mul or multiple operator is a type of field update operator. $mul operator multiplies the value of the field by a number.

Important Points

  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

Syntax:

{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }

MongoDB $mul Operator Example

Database: Fruits 



Collection: Details 

Document: two documents that contain the details of the fruits in the form of field-value pairs.



Example 1: Multiplying the value of a field

In this example, we are multiplying the value of the price field by 2.10 in the document which matches the specified condition, i.e., name = mango.

Query:

db.Details.update({name: "mango"}, {$mul: {price: NumberDecimal("2.10")}})

Output:

Example 2: Multiplying the value of a field in the embedded/nested document

In this example, we are multiplying the value of quantity.tQuantity field by 3 in the document that matches the specified condition, i.e., name = mango.

Query:

db.Details.update({name: "mango"}, {$mul: {"quantity.tQuantity": 3}})

Output:

Example 3: Using $mul operator to a non-existing field

In this example, we are applying $mul operator to a non-existing field in the document that matches the specified condition, i.e., name = apple.

Query:

db.Details.update({name: "apple"}, {$mul: {"batchNumber":NumberInt(230)}})

Output:

Example 4: Using $mul operator to multiply mixed numeric type

In this example, we are multiplying the value(float type) of the price field in the document that matches the specified condition, i.e., name = apple.

Query:

db.Details.update({name: "apple"}, {$mul: {price: NumberDecimal(5)}})

Output:

Key Takeaways About $mul Operator

Article Tags :