In MongoDB, the $sqrt
aggregation pipeline operator calculates the square root of a positive number and returns the result as a double.
$sqrt
accepts any valid expression that resolves to a non-negative number.
Example
Suppose we have a collection called test
with the following documents:
{ "_id" : 1, "data" : 100 } { "_id" : 2, "data" : 250 }
We can use the $sqrt
operator to return the square root of the data
field:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 1, 2 ] } } },
{ $project: {
squareRoot: { $sqrt: "$data" }
}
}
]
)
Result:
{ "_id" : 1, "squareRoot" : 10 } { "_id" : 2, "squareRoot" : 15.811388300841896 }
Negative Values
The $sqrt
operator only accepts non-negative numbers.
Suppose we add the following document to our collection:
{ "_id" : 3, "data" : -100 }
Let’s apply the the $sqrt
operator against that document:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 3 ] } } },
{ $project: {
squareRoot: { $sqrt: "$data" }
}
}
]
)
Result:
uncaught exception: Error: command failed: { "ok" : 0, "errmsg" : "$sqrt's argument must be greater than or equal to 0", "code" : 28714, "codeName" : "Location28714" } : 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
This error tells us that $sqrt’s argument must be greater than or equal to 0.
Null Values
Null values return null
when using the $sqrt
operator.
Suppose we add the following document to our collection:
{ "_id" : 4, "data" : null }
Let’s apply the the $sqrt
operator against that document:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 4 ] } } },
{ $project: {
squareRoot: { $sqrt: "$data" }
}
}
]
)
Result:
{ "_id" : 4, "squareRoot" : null }
We can see that the result is null
.
NaN Values
If the argument resolves to NaN
, $sqrt
returns NaN
.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
squareRoot: { $sqrt: "$data" * 1 }
}
}
]
)
Result:
{ "_id" : 1, "squareRoot" : NaN }
Non-Existent Fields
If the $sqrt
operator is applied against a field that doesn’t exist, null
is returned.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
squareRoot: { $sqrt: "$age" }
}
}
]
)
Result:
{ "_id" : 1, "squareRoot" : null }