$stdDevSamp (aggregation)
Nesta página
Definição
Alterado na versão 5.0.
Calculates the sample standard deviation of the input values. Use if
the values encompass a sample of a population of data from which
to generalize about the population. $stdDevSamp
ignores
non-numeric values.
If the values represent the entire population of data or you do not
wish to generalize about a larger population, use
$stdDevPop
instead.
$stdDevSamp
está disponível nesses estágios:
$setWindowFields
(Disponível a partir do MongoDB 5.0)
Sintaxe
Quando utilizado nos estágios $bucket
, $bucketAuto
, $group
e $setWindowFields
, $stdDevSamp
tem esta sintaxe:
{ $stdDevSamp: <expression> }
Quando usado em outros estágios compatíveis, $stdDevSamp
tem uma de duas sintaxes:
$stdDevSamp
tem uma expressão especificada como seu operando:{ $stdDevSamp: <expression> } $stdDevSamp
tem uma lista de expressões especificadas como seu operando:{ $stdDevSamp: [ <expression1>, <expression2> ... ] }
O argumento para $stdDevSamp
pode ser qualquer expressão, desde que seja resolvida em uma array.
Para mais informações sobre expressões, consulte Operadores de Expressão.
Comportamento
Tipo de resultado
$stdDevSamp
returns the sample standard deviation of the
input values as a double
.
Valores não numéricos
$stdDevSamp
ignores non-numeric values. If all operands for a
sum are non-numeric, $stdDevSamp
returns null
.
Valor único
Se a amostra consistir em um único valor numérico, $stdDevSamp
retornará null
.
Operando de array
In the $group
and $setWindowFields
stages,
if the expression resolves to an array, $stdDevSamp
treats the
operand as a non-numerical value.
Nos outros estágios suportados:
Com uma única expressão como operando, se a expressão for resolvida em uma array, percorre a array para operar nos elementos numéricos da array e retornar um único
$stdDevSamp
valor.Com uma lista de expressões como seu operando, se qualquer uma das expressões for resolvida para uma array,
$stdDevSamp
não atravessará a array, mas tratará a array como um valor não numérico.
Valores da janela
Comportamento com valores em uma $setWindowFields
janela de estágio :
Ignora valores não numéricos, valores
null
e campos ausentes em uma janela.Se a janela estiver vazia, retorna
null
.Se a janela contiver um valor
NaN
, retornanull
.Se a janela contiver
Infinity
valores, retornanull
.Se nenhum dos pontos anteriores se aplicar, retorna um valor
double
.
Exemplos
Usar no estágio $group
A collection users
contains documents with the following fields:
{_id: 0, username: "user0", age: 20} {_id: 1, username: "user1", age: 42} {_id: 2, username: "user2", age: 28} ...
To calculate the standard deviation of a sample of users, following
aggregation operation first uses the $sample
pipeline to
sample 100 users, and then uses $stdDevSamp
calculates the
standard deviation for the sampled users.
db.users.aggregate( [ { $sample: { size: 100 } }, { $group: { _id: null, ageStdDev: { $stdDevSamp: "$age" } } } ] )
The operation returns a result like the following:
{ "_id" : null, "ageStdDev" : 7.811258386185771 }
Usar no estágio $setWindowFields
Novidades na versão 5.0.
Crie uma collection cakeSales
que contenha vendas de bolo nos estados da Califórnia (CA
) e de Washington (WA
):
db.cakeSales.insertMany( [ { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"), state: "CA", price: 13, quantity: 120 }, { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"), state: "WA", price: 14, quantity: 140 }, { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"), state: "CA", price: 12, quantity: 145 }, { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"), state: "WA", price: 13, quantity: 104 }, { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"), state: "CA", price: 41, quantity: 162 }, { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"), state: "WA", price: 43, quantity: 134 } ] )
This example uses $stdDevSamp
in the
$setWindowFields
stage to output the sample standard
deviation of the quantity
values of the cake sales for each
state
:
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { stdDevSampQuantityForState: { $stdDevSamp: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
No exemplo:
partitionBy: "$state"
divide dos documentos na coleção porstate
. Existem divisões paraCA
eWA
.sortBy: { orderDate: 1 }
classifica os documentos em cada divisão pororderDate
em ordem crescente (1
), de modo que aorderDate
mais antiga seja a primeira.
output
sets thestdDevSampQuantityForState
field to the sample standard deviation of thequantity
values using$stdDevSamp
that is run in a documents window.The window contains documents between an
unbounded
lower limit and thecurrent
document in the output. This means$stdDevSamp
returns the sample standard deviation of thequantity
values for the documents between the beginning of the partition and the current document.
In this output, the sample standard deviation quantity
value for
CA
and WA
is shown in the stdDevSampQuantityForState
field:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"), "state" : "CA", "price" : 41, "quantity" : 162, "stdDevSampQuantityForState" : null } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"), "state" : "CA", "price" : 13, "quantity" : 120, "stdDevSampQuantityForState" : 29.698484809834994 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"), "state" : "CA", "price" : 12, "quantity" : 145, "stdDevSampQuantityForState" : 21.1266025033211 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"), "state" : "WA", "price" : 43, "quantity" : 134, "stdDevSampQuantityForState" : null } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"), "state" : "WA", "price" : 13, "quantity" : 104, "stdDevSampQuantityForState" : 21.213203435596427 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"), "state" : "WA", "price" : 14, "quantity" : 140, "stdDevSampQuantityForState" : 19.28730152198591 }