mongo-db
  1. mongo-db-multiply-operator

MongoDB $multiply Operator

The $multiply operator in MongoDB is used to multiply numeric values in aggregation expressions. It is commonly employed within the $project stage of an aggregation pipeline to perform mathematical multiplication on field values. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using the $multiply operator in MongoDB aggregation.

Syntax

{ $multiply: [ <expression1>, <expression2>, ... ] }
  • <expression1>, <expression2>, ...: Numeric expressions or field references to be multiplied.

Example

Consider a collection named products with documents containing price and quantity fields. We want to calculate the total cost by multiplying the price and quantity during an aggregation.

db.products.aggregate([
  {
    $project: {
      product_name: 1,
      total_cost: { $multiply: ["$price", "$quantity"] }
    }
  }
]);

Output

The output will display documents with the product_name and calculated total_cost fields.

[
  { "_id": ObjectId("..."), "product_name": "Laptop", "total_cost": 1200 },
  { "_id": ObjectId("..."), "product_name": "Phone", "total_cost": 800 },
  // ... other documents
]

Explanation

  • The $multiply operator is used within the $project stage to calculate the product of the price and quantity fields for each document.
  • The result is included in the output as the total_cost field.

Use

The $multiply operator in MongoDB is used for:

  • Calculating the product of numeric values in aggregation pipelines.
  • Performing mathematical operations on fields within the $project stage.
  • Creating derived fields based on multiplication of existing fields.

Important Points

  • The $multiply operator can take any number of expressions as arguments.
  • It is commonly used in conjunction with other arithmetic operators within aggregation pipelines.
  • Ensure that the expressions provided are valid and result in numeric values.

Summary

The $multiply operator in MongoDB provides a way to perform multiplication operations during aggregation. It is particularly useful for calculating derived values, such as total costs or scores, based on numeric fields in documents. Understanding how to use the $multiply operator is valuable for MongoDB developers working with aggregation pipelines to transform and analyze data.

Published on: