MongoDB $ln OperatorWhat is the $ln operator in MongoDB?MongoDB provides a variety of arithmetic expression operators. The $ln operator is one of those operators. The $ln operator is used to calculate the natural logarithm (ln, i.e. loge) of a number, and it returns the result as a double. The $ln operator is used in the aggregation-pipeline stages. The natural logarithm (ln) is the logarithm of the base of the mathematical constant "e", where e is an irrational number starting with 2.7182818284590452353602874713527. The "e" is also known as the Euler number. In JavaScript, we use Math.E to represent "e". Syntax of the $ln operator:Where, the < number > can be any valid expression that resolves to a non-negative number (i.e. 0, 1, 2, 3 ….n). Important point
Examples:Suppose we have a collection of the products with the following documents. Example 1: Using $ln operator In this example, we are computing the natural logarithm of a "value" field using the $ln operator. Output: { "name" : "toys", "value" : 10, "natural_log" : 2.30258509299 } { "name" : "pen", "value" : 5, "natural_log" : 1.60943791243 } { "name" : "phone", "value" : 8, "natural_log" : 2.07944154168 } { "name" : "charger", "value" : 20, "natural_log" : 2.99573227355 } { "name" : "laptop", "value" : 30, "natural_log" : 3.40119738166 } Suppose we add the following documents to our collection: { { "_id" : 6, "name" : "headphone", "value" : -10 } { "_id" : 7, "name" : "pen", "value" : -20 } } Example 2: Out of Range Values In this example, we are computing the natural logarithm of a "value" field using the $ln operator. Output: uncaught exception : Error : command failed : { "ok": 0, "errmsg": "$ln's argument must be a positive number, but is -20", "code": 28766, "codeName": "Location28766" }: aggregate failed: _getErrorWithCode@src/mongo/shell/utils.js : 25 : 13 doassert@src/mongo/shell/assert.js : 18 : 14 _assertCommandWorked@src/mongo/shell/assert.js : 639 : 17 assert.commandWorked@src/mongo/shell/assert.js : 729 : 16 DB.prototype._runAggregate@src/mongo/shell/db.js : 266 : 5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js : 1058 : 12 @(shell) : 1 : 1 Suppose we add one more document to our collection: { { "_id" : 8, "name" : "phone", "value" : null } } Example 3: Null Values In this example, we are computing the natural logarithm of a "value" field using the $ln operator. Output: { "name" : "phone", "value" : null, "natural_log" : null } Example 4: Non-Existent Fields If the $ln operator is applied against a field that does not exist, null is returned. In this example, we are computing the natural logarithm of a "value" field using the $ln operator. Output: { "name" : "toys", "value" : 10, "natural_log" : null } Next TopicMongoDB $log10 Operator |