Introduction to MongoDB $exp Operator

The $exp operator is a mathematical operator in MongoDB that returns the value of the natural exponential function. It can be used for calculations in query conditions, update operations, aggregation pipelines, and more.

Syntax

The syntax of the $exp operator is as follows:

{ $exp: <expression> }

where <expression> represents a numerical expression, which can be a document field, constant, or the result of another numerical operation.

Use Cases

When performing aggregation calculations in MongoDB, it is often necessary to perform numerical processing on data, including exponential operations. The $exp operator can be used to calculate the exponential value of a field or to perform exponential operations in an aggregation pipeline.

Examples

Here are two examples of using the $exp operator:

Example 1: Calculating Exponential Values

Suppose we have a collection of documents that contains a numerical field x, and we want to calculate the natural exponential value of x. We can use the $exp operator to achieve this:

Original data:

{ "_id" : 1, "x" : 0 }
{ "_id" : 2, "x" : 1 }
{ "_id" : 3, "x" : 2 }

Query statement:

db.collection.aggregate([{ $project: { exp_x: { $exp: "$x" } } }])

Result:

{ "_id" : 1, "exp_x" : 1 }
{ "_id" : 2, "exp_x" : 2.718281828459045 }
{ "_id" : 3, "exp_x" : 7.38905609893065 }

Example 2: Performing Exponential Operations with $exp

Suppose we want to calculate the first 10 terms of the natural exponential series. We can use the $exp operator in an aggregation pipeline to perform the calculation.

Query statement:

db.collection.aggregate([
  { $group: { _id: null, exp: { $push: { $exp: "$$ROOT._id" } } } },
  { $project: { _id: 0, exp: 1 } }
])

Result:

{
  "exp" : [
    2.718281828459045,
    7.38905609893065,
    20.085536923187668,
    54.598150033144236,
    148.4131591025766,
    403.4287934927351,
    1096.6331584284585,
    2980.9579870417283,
    8103.083927575384,
    22026.465794806718
  ]
}

Conclusion

The $exp operator is a useful mathematical operator in MongoDB that can be used to calculate the value of the natural exponential function or perform exponential operations in aggregation calculations. Using the $exp operator makes it easy to process numerical data.