mongo-db
  1. mongo-db-divide-operator

$divide Operator - (MongoDB Misc)

The $divide operator is a mathematical aggregation expression in MongoDB that performs the division of two numbers or expressions. This page discusses the syntax, examples, output, explanation, use, important points, and summary of the $divide operator in MongoDB.

Syntax

The $divide operator syntax is as follows:

{ $divide: [ <expression1>, <expression2> ] }

Here, <expression1> and <expression2> are two numerical expressions that are to be divided.

Example

Consider a collection named sales with the following documents:

[
  {_id: 1, product: 'A', price: 100, quantity: 10 },
  {_id: 2, product: 'B', price: 200, quantity: 5 },
  {_id: 3, product: 'C', price: 150, quantity: 12 },
  {_id: 4, product: 'D', price: 175, quantity: 8 },
  {_id: 5, product: 'E', price: 250, quantity: 15 }
]

To calculate the average price-per-item, you can use the $divide operator, as shown below:

db.sales.aggregate([
  {
    $project: {
      _id: 0,
      product: 1,
      price_per_item: { $divide: [ "$price", "$quantity" ] }
    }
  }
])

The above query returns the following output:

[
  { product: 'A', price_per_item: 10 },
  { product: 'B', price_per_item: 40 },
  { product: 'C', price_per_item: 12.5 },
  { product: 'D', price_per_item: 21.875 },
  { product: 'E', price_per_item: 16.666666666666668 }
]

Output

The $divide operator returns the result of dividing the first expression by the second expression.

Explanation

MongoDB's $divide operator divides two numerical expressions and returns the quotient as a double.

Use

The $divide operator is used in aggregation pipelines to perform mathematical operations.

Important Points

The $divide operator requires two numerical expressions as arguments. If one or both of the expressions are not numerical, the operator returns an error.

Summary

In this page, we discussed the $divide operator in MongoDB. We covered its syntax, examples, output, explanation, use, and important points. The $divide operator is a mathematical aggregation expression used to divide two numerical expressions. Using this operator, you can perform calculations and transformations of numerical data in MongoDB.

Published on: