$exp Operator - (MongoDB Misc)
In MongoDB, you can use the $exp
operator in aggregation pipelines to perform exponential calculations on numeric values. In this page, we will discuss the syntax, examples, output, explanation, use, important points, and summary of the $exp
operator in MongoDB.
Syntax
The $exp
operator has the following syntax:
{ $exp: <expression> }
The <expression>
is a numeric value that will be exponentiated.
Example
Consider the following sample collection of products:
[
{ "product": "book", "price": 25 },
{ "product": "notebook", "price": 12 },
{ "product": "pen", "price": 2 }
]
To exponentiate the price
field of each product by 2, we can use the $exp
operator in an aggregation pipeline like this:
db.products.aggregate([
{ $project: { product: 1, squaredPrice: { $exp: "$price" } } }
])
The output will be:
[
{ "product": "book", "squaredPrice": 7.200489933738588e+10 },
{ "product": "notebook", "squaredPrice": 1.627547914163934e+5 },
{ "product": "pen", "squaredPrice": 7.3890560989306495 }
]
Explanation
The $exp
operator performs exponential calculations on numeric values. It returns natural exponentiation, which is the mathematical constant e raised to the power of the specified number. The <expression>
can be any valid numeric expression.
Use
The $exp
operator can be used in aggregation pipelines to perform exponential calculations on fields containing numeric data. This can be useful for various situations, like when you need to balance data by its exponential value.
Important Points
- The
$exp
operator is used for exponential calculations on numeric values. - The
<expression>
can be any valid numeric expression.
Summary
In this page, we discussed the $exp
operator in MongoDB. We covered the syntax, example, output, explanation, use, important points, and summary of the $exp
operator. By using the $exp
operator in aggregation pipelines, you can exponentiate fields containing numeric data in your MongoDB documents.