Menu Docs

$stdDevSamp (aggregation)

$stdDevSamp

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:

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.

$stdDevSamp returns the sample standard deviation of the input values as a double.

$stdDevSamp ignores non-numeric values. If all operands for a sum are non-numeric, $stdDevSamp returns null.

Se a amostra consistir em um único valor numérico, $stdDevSamp retornará null.

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.

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 , retorna null.

  • Se a janela contiver Infinity valores, retorna null.

  • Se nenhum dos pontos anteriores se aplicar, retorna um valor double .

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 }

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 por state. Existem divisões para CA e WA.

  • sortBy: { orderDate: 1 } classifica os documentos em cada divisão por orderDate em ordem crescente (1), de modo que a orderDate mais antiga seja a primeira.

  • output sets the stdDevSampQuantityForState field to the sample standard deviation of the quantity values using $stdDevSamp that is run in a documents window.

    The window contains documents between an unbounded lower limit and the current document in the output. This means $stdDevSamp returns the sample standard deviation of the quantity 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 }