Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

$stdDevSamp (operador de acumulación)

$stdDevSamp

Cambiado en la versión 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.

Si los valores representan toda la población de datos o si no deseas generalizar sobre una población más grande, utiliza $stdDevPop en su lugar.

$stdDevSamp está disponible en estas etapas:

When used in the $bucket, $bucketAuto, $group, and $setWindowFields stages, $stdDevSamp has this syntax:

{ $stdDevSamp: <expression> }

When used in other supported stages, $stdDevSamp has one of two syntaxes:

  • $stdDevSamp tiene una expresión especificada como su operando:

    { $stdDevSamp: <expression> }
  • $stdDevSamp tiene una lista de expresiones especificadas como su operando:

    { $stdDevSamp: [ <expression1>, <expression2> ... ] }

The argument for $stdDevSamp can be any expression as long as it resolves to an array.

Para obtener más información sobre las expresiones, consulta Expresiones.

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

If the sample consists of a single numeric value, $stdDevSamp returns null.

In the $group and $setWindowFields stages, if the expression resolves to an array, $stdDevSamp treats the operand as a non-numerical value.

En las otras etapas admitidas:

  • With a single expression as its operand, if the expression resolves to an array, $stdDevSamp traverses into the array to operate on the numeric elements of the array to return a single value.

  • With a list of expressions as its operand, if any of the expressions resolves to an array, $stdDevSamp does not traverse into the array but instead treats the array as a non-numeric value.

Comportamiento con valores en una $setWindowFields etapa ventana:

  • Ignora los valores no numéricos, valores null y los campos faltantes en una ventana.

  • Si la ventana está vacía, devuelve null.

  • Si la ventana contiene un valor de NaN, devuelve null.

  • Si la ventana contiene Infinity valores, retorna null.

  • Si ninguno de los puntos anteriores aplica, devuelve un valor de double.

Una colección users contiene documentos con los siguientes campos:

db.users.insertMany( [
{ _id: 0, username: "user0", age: 20 },
{ _id: 1, username: "user1", age: 42 },
{ _id: 2, username: "user2", age: 28 }
] )

Para calcular la desviación estándar de una muestra de usuarios, la siguiente operación de agregación primero utiliza la canalización para $sample muestrear 100 usuarios y luego utiliza para $stdDevSamp calcular la desviación estándar para los usuarios muestreados.

db.users.aggregate(
[
{ $sample: { size: 100 } },
{ $group: { _id: null, ageStdDev: { $stdDevSamp: "$age" } } }
]
)

La operación devuelve un resultado como el siguiente:

{ _id: null, ageStdDev: 7.811258386185771 }

Nuevo en la versión 5.0.

Crea una colección de cakeSales que incluya ventas de pasteles en el estado de California (CA) y 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" ]
}
}
}
}
}
] )

En el ejemplo:

  • partitionBy: "$state" particiona los documentos de la colección en state. Existen particiones para CA y WA.

  • sortBy: { orderDate: 1 } ordena los documentos de cada partición por orderDate en orden ascendente (1), de modo que el orderDate más antiguo sea el primero.

  • 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.

En esta salida, se muestra el valor quantity de la desviación estándar de la muestra para CA y WA en el campo stdDevSampQuantityForState:

{ _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 }