MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and an $subtract operator is one of them. This operator is used to subtract two numbers and return the difference in the numbers or to subtract two dates and return the difference in the milliseconds, or subtracts date and number in milliseconds and returns the date. Show Syntax: { $subtract: [ <expression1>, <expression2> ] } Here, the given arguments must be a valid expression like numbers or a date, and the second argument is subtracted from the first argument. If you are subtracting a number from a date, then the first argument of this operator is a date. Examples: In the following examples, we are working with:
Using $subtract operator subtract two numbers: In this example, we are going to subtract 5*24*60*60000 milliseconds (i.e., 5 days) from the value of projectEndDate field using a $subtract operator. In MongoDB, you can use the 5 aggregation pipeline operator to subtract numbers and/or dates.Specifically, 5 can do the following three things:
The 5 operator accepts exactly two arguments. Passing the wrong number of arguments results in an error.ExampleReturn the sum of the "Quantity" field in the "OrderDetails" table: SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails; Try it Yourself »Definition and UsageThe SUM() function calculates the sum of a set of values. Note: NULL values are ignored. SyntaxParameter ValuesParameterDescriptionexpressionRequired. A field or a formulaTechnical DetailsMongoDB provides a variety of arithmetic expression operators. The $subtract operator is one of those operators. This operator is used to subtract two numbers or dates and returns the difference.
Syntax of the $subtract operator:Note: The arguments must be a valid expression, such as a number or a date. In this operator, the second argument is subtracted by the first argument. If you want to subtract a number from a date, the first argument should always be a date.Examples:Suppose we have a collection of the students with the following documents. Example 1: Subtract two numbers using the $subtract operator In this example, we are going to subtract the 250 from the "start_date" field using the $subtract operator. Sometimes your data source does not contain a field (or column) that you need for your analysis. For example, your data source might contain fields with values for Sales and Profit, but not for Profit Ratio. If this is the case, you can create a calculated field for Profit Ratio using data from the Sales and Profit fields. This topic demonstrates how to create a simple calculated field using an example. Step 1: Create the calculated field
Step 2: Enter a formula
|