$mul

Multiplies the value of a field by a specified number, creating the field with value zero if it doesn't exist, useful for scaling and percentage operations.

Syntax

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

Parameters

fieldstringrequired

The name of the field to multiply

numbernumberrequired

The number to multiply the field value by

Examples

Apply percentage increase

Apply a 10% increase to total sales (multiply by 1.1)

Query:

db.stores.updateOne({ "_id": "store-001" }, { $mul: { "sales.totalSales": 1.1 } })

Output:

Increases totalSales by 10% through multiplication

Apply discount

Apply a 20% discount to sales figures (multiply by 0.8)

Query:

db.stores.updateOne({ "_id": "store-001" }, { $mul: { "sales.totalSales": 0.8 } })

Output:

Reduces totalSales by 20% through multiplication

Multiple field operations

Apply different multipliers to multiple fields simultaneously

Query:

db.stores.updateOne({ "_id": "store-001" }, { $mul: { "staff.totalStaff.fullTime": 1.5, "staff.totalStaff.partTime": 2, "sales.totalSales": 1.25 } })

Output:

Applies different scaling factors to staff counts and sales

Array element multiplication

Apply multipliers to specific elements within arrays

Query:

db.stores.updateOne({ "_id": "store-001", "sales.salesByCategory.categoryName": "Electronics" }, { $mul: { "sales.salesByCategory.$.totalSales": 1.15 } })

Output:

Increases sales for the matching category by 15%

Handle negative and zero values

Apply negative multipliers and zero values for special operations

Query:

db.stores.updateOne({ "_id": "store-001" }, { $mul: { "sales.totalSales": -1, "staff.totalStaff.fullTime": 0 } })

Output:

Makes totalSales negative and sets fullTime to zero

Related