In MongoDB, the $log10
aggregation pipeline operator calculates the log base 10 of a number and returns the result as a double.
$log10
accepts any valid expression that resolves to a non-negative number.
The $log10
operator was introduced in MongoDB 3.2.
Example
Suppose we have a collection called test
with the following document:
{ "_id" : 1, "data" : 0.5 }
We can use the $log10
operator to return the log base 10 of the data
field:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
result: { $log10: "$data" }
}
}
]
)
Result:
{ "result" : -0.3010299956639812 }
Out of Range Values
As mentioned, the $log10
operator accepts any valid expression that resolves to a non-negative number. Values outside of that range will cause an error.
Suppose we add the following document to our collection:
{ "_id" : 2, "data" : -3 }
Let’s run the the $log10
operator against that document:
db.test.aggregate(
[
{ $match: { _id: 2 } },
{ $project: {
_id: 0,
result: { $log10: "$data" }
}
}
]
)
Result:
uncaught exception: Error: command failed: { "ok" : 0, "errmsg" : "$log10's argument must be a positive number, but is -3", "code" : 28761, "codeName" : "Location28761" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:618:17 assert.commandWorked@src/mongo/shell/assert.js:708:16 DB.prototype._runAggregate@src/mongo/shell/db.js:266:5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1046:12 @(shell):1:1
Null Values
Null values return null
when using the $log10
operator.
Suppose we add the following document to our collection:
{ "_id" : 3, "data" : null }
Let’s run the the $log10
operator against that document:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{ $project: {
_id: 0,
result: { $log10: "$data" }
}
}
]
)
Result:
{ "result" : null }
We can see that the result is null
.
NaN Values
If the argument resolves to NaN
, $log10
returns NaN
.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
result: { $log10: 1 * "$data" }
}
}
]
)
Result:
{ "result" : NaN }
Non-Existent Fields
If the $log10
operator is applied against a field that doesn’t exist, null
is returned.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
result: { $log10: "$name" }
}
}
]
)
Result:
{ "result" : null }