mongo-db
  1. mongo-db-subtract-operator

$subtract Operator - (MongoDB Misc)

MongoDB provides various operators to perform calculations on documents. One of these operators is the $subtract operator, which subtracts the specified values from each other.

In this article, we will discuss the syntax, usage, examples, and important points to consider while using the $subtract operator in MongoDB.

Syntax

The syntax of the $subtract operator is as follows:

{ $subtract: [ <expression1>, <expression2>, ... <expressionN> ] }

Here, <expression1> and <expression2> are the values that are subtracted from each other.

Example

Let's see how to use the $subtract operator in a sample MongoDB dataset.

Consider a collection named orders that stores information about various orders. The following is an example of the documents present in the orders collection:

{
   "_id" : 1,
   "item" : "abc",
   "price" : 20,
   "quantity" : 5
}
{
   "_id" : 2,
   "item" : "def",
   "price" : 10   "quantity" : 2
}
{
   "_id" : 3,
   "item" : "xyz",
   "price" : 5,
   "quantity" : 10
}

We can use the $subtract operator to calculate the total profit generated by each order, which is calculated by the formula price * quantity - cost.

db.orders.aggregate(
   [
      {
         $project:
           {
             _id: 0,
             item: 1,
             profit: { $subtract: [ { $multiply: [ "$price", "$quantity" ] }, 100 ] }
           }
      }
   ]
)

In the above example, the $multiply operator calculates the total cost of each order, which is $price * $quantity, and the $subtract operator subtracts 100 from it to get the profit generated from each order.

Output

The above query will generate the following output:

{ "item" : "abc", "profit" : 100 }
{ "item" : "def", "profit" : 10 }
{ "item" : "xyz", "profit" : 50 }

Explanation

The $subtract operator subtracts the second value from the first value and returns the result.

In the above example, we have used the $multiply operator to calculate the total cost of each order, which is then subtracted from 100 to calculate the profit.

Use

The $subtract operator can be used to perform various calculations on MongoDB data. Some common use cases include calculating the difference between two dates, subtracting the cost of goods sold from the sales price to calculate profit, etc.

Important Points

  • The $subtract operator subtracts the second value from the first value and returns the result.
  • The $subtract operator can be used in conjunction with other aggregation operators to perform complex calculations.

Summary

In this article, we have discussed the syntax, usage, examples, and important points to consider while using the $subtract operator in MongoDB. With the help of the $subtract operator, we can perform various calculations on MongoDB data and generate meaningful insights.

Published on: