$sqrt (aggregation)
Nesta página
Definição
$sqrt
Calculates the square root of a positive number and returns the result as a double.
$sqrt
tem a seguinte sintaxe:{ $sqrt: <number> } The argument can be any valid expressão as long as it resolves to a non-negative number. For more information on expressions, see Operadores de Expressão.
Comportamento
O tipo de retorno padrão é um double
. Se pelo menos um operando for decimal
, o tipo de retorno será decimal.
Se o argumento for resolvido para um valor de null
ou se referir a um campo ausente, $sqrt
retornará null
. Se o argumento se resolve em NaN
, $sqrt
retorna NaN
.
$sqrt
errors on negative numbers.
Exemplo | Resultados |
---|---|
|
|
|
|
|
|
Exemplo
Uma coleção points
contém os seguintes documentos:
{ _id: 1, p1: { x: 5, y: 8 }, p2: { x: 0, y: 5} } { _id: 2, p1: { x: -2, y: 1 }, p2: { x: 1, y: 5} } { _id: 3, p1: { x: 4, y: 4 }, p2: { x: 4, y: 0} }
The following example uses $sqrt
to calculate the
distance between p1
and p2
:
db.points.aggregate([ { $project: { distance: { $sqrt: { $add: [ { $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] }, { $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] } ] } } } } ])
A operação retorna os seguintes resultados:
{ "_id" : 1, "distance" : 5.830951894845301 } { "_id" : 2, "distance" : 5 } { "_id" : 3, "distance" : 4 }