MongoDB $exp

In MongoDB, the $exp aggregation pipeline operator raises Euler’s number (i.e. e ) to the specified exponent and returns the result.

The exponent can be any valid expression that resolves to a number.

Euler’s number is a mathematical constant approximately equal to 2.7182818284590452353602874713527. This number is only approximate because Euler’s number is irrational and its digits continue forever without repeating. Euler’s number is the base of the natural logarithm.

Example

Suppose we have a collection called test with the following documents

{ "_id" : 1, "data" : 2 }
{ "_id" : 2, "data" : 3 }
{ "_id" : 3, "data" : -2 }
{ "_id" : 4, "data" : -3 }
{ "_id" : 5, "data" : 0 }

Here’s an example of applying the $exp operator to the data field:

db.test.aggregate(
   [
     { $match: { _id: { $in: [ 1, 2, 3, 4, 5 ] } } },
     {
       $project:
          {
            _id: 0,
            data: 1,
            result: { $exp: "$data" }
          }
     }
   ]
)

Result:

{ "data" : 2, "result" : 7.38905609893065 }
{ "data" : 3, "result" : 20.085536923187668 }
{ "data" : -2, "result" : 0.1353352832366127 }
{ "data" : -3, "result" : 0.049787068367863944 }
{ "data" : 0, "result" : 1 }

Null Values

If the expression resolves to null, then null is returned.

Suppose our collection contains the following document:

{ "_id" : 6, "data" : null }

Now let’s apply $exp to that document:

db.test.aggregate(
   [
     { $match: { _id: 6 } },
     {
       $project:
          {
            _id: 0,
            data: 1,
            result: { $exp: "$data" }
          }
     }
   ]
)

Result:

{ "data" : null, "result" : null }

Infinity

Suppose we have the following documents in our collection:

{ "_id" : 7, "data" : Infinity }
{ "_id" : 8, "data" : -Infinity }

Here’s what happens when we apply $exp to Infinity and -Infinity:

db.test.aggregate(
   [
     { $match: { _id: { $in: [ 7, 8 ] } } },
     {
       $project:
          {
            _id: 0,
            data: 1,
            result: { $exp: "$data" }
          }
     }
   ]
)

Result:

{ "data" : Infinity, "result" : Infinity }
{ "data" : -Infinity, "result" : 0 }

Missing Fields

Applying $exp to a missing field returns null.

Example:

db.test.aggregate(
   [
     {
       $project:
          {
            result: { $exp: "$age" }
          }
     }
   ]
)

Result:

{ "_id" : 1, "result" : null }
{ "_id" : 2, "result" : null }
{ "_id" : 3, "result" : null }
{ "_id" : 4, "result" : null }
{ "_id" : 5, "result" : null }
{ "_id" : 6, "result" : null }
{ "_id" : 7, "result" : null }
{ "_id" : 8, "result" : null }

In this example we apply the $exp operator to a non-existent field called age. The result is null in all cases.