Definición
Cambiado en la versión 5.0.
Returns the minimum value. $min compares both value and type, using the specified BSON comparison order for values of different types.
$min está disponible en estas etapas:
$setWindowFields(Disponible a partir de MongoDB 5.0)
Sintaxis
When used in the $bucket, $bucketAuto, $group, and $setWindowFields stages, $min has this syntax:
{ $min: <expression> }
When used in other supported stages, $min has one of two syntaxes:
$mintiene una expresión especificada como su operando:{ $min: <expression> } $mintiene una lista de expresiones especificadas como su operando:{ $min: [ <expression1>, <expression2> ... ] }
Para obtener más información sobre las expresiones, consulta Expresiones.
Comportamiento
Tipo de resultado
$min compara los datos de entrada siguiendo el orden de comparación BSON para determinar el tipo de resultado adecuado. Cuando los datos de entrada contienen múltiples tipos de datos, el tipo de output $min es el más bajo en el orden de comparación.
Valores nulos o faltantes
If some, but not all, documents for the $min operation have either a null value for the field or are missing the field, the $min operator only considers the non-null and the non-missing values for the field.
If all documents for the $min operation have null value for the field or are missing the field, the $min operator returns null for the minimum value.
Arreglo Operand
In the $group and $setWindowFields stages, if the expression resolves to an array, $min does not traverse the array and compares the array as a whole.
En las otras etapas admitidas:
With a single expression as its operand, if the expression resolves to an array,
$mintraverses 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,
$mindoes not traverse into the array but instead treats the array as a non-numeric value.
Valores iguales
Si varios valores se comparan como iguales, $min puede devolver cualquiera de esos valores. No hay garantías de qué valor igual devuelve $min.
Por ejemplo, en una intercalación sin distinción entre mayúsculas y minúsculas, "a" y "A" pueden compararse como iguales. No hay garantías de cuál se devolverá.
Ejemplos
Uso en la etapa $group
Considera una colección sales con los siguientes documentos:
db.sales.insertMany( [ { _id : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }, { _id : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }, { _id : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }, { _id : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }, { _id : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") } ] )
Grouping the documents by the item field, the following operation uses the $min accumulator to compute the minimum amount and minimum quantity for each grouping.
db.sales.aggregate( [ { $group: { _id: "$item", minQuantity: { $min: "$quantity" } } } ] )
La operación devuelve los siguientes resultados:
{ "_id" : "xyz", "minQuantity" : 5 } { "_id" : "jkl", "minQuantity" : 1 } { "_id" : "abc", "minQuantity" : 2 }
Uso en la etapa $project
Una colección students contiene los siguientes documentos:
db.students.insertMany( [ { _id: 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }, { _id: 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }, { _id: 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 } ] )
The following example uses the $min in the $project stage to calculate the minimum quiz scores, the minimum lab scores, and the minimum of the final and the midterm:
db.students.aggregate([ { $project: { quizMin: { $min: "$quizzes"}, labMin: { $min: "$labs" }, examMin: { $min: [ "$final", "$midterm" ] } } } ])
La operación da como resultado los siguientes documentos:
{ "_id" : 1, "quizMin" : 6, "labMin" : 5, "examMin" : 75 } { "_id" : 2, "quizMin" : 9, "labMin" : 8, "examMin" : 80 } { "_id" : 3, "quizMin" : 4, "labMin" : 5, "examMin" : 70 }
Uso en la etapa $setWindowFields
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 $min in the $setWindowFields stage to output the minimum quantity of cake sales for each state:
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { minimumQuantityForState: { $min: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
En el ejemplo:
partitionBy: "$state"particiona los documentos de la colección enstate. Existen particiones paraCAyWA.sortBy: { orderDate: 1 }ordena los documentos de cada partición pororderDateen orden ascendente (1), de modo que elorderDatemás antiguo sea el primero.
outputsets theminimumQuantityForStatefield to the minimumquantityvalue using$minthat is run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument in the output. This means$minreturns the minimumquantityfor the documents between the beginning of the partition and the current document.
En esta salida, el mínimo quantity para CA y WA se muestra en el campo minimumQuantityForState:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"), "state" : "CA", "price" : 41, "quantity" : 162, "minimumQuantityForState" : 162 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"), "state" : "CA", "price" : 13, "quantity" : 120, "minimumQuantityForState" : 120 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"), "state" : "CA", "price" : 12, "quantity" : 145, "minimumQuantityForState" : 120 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"), "state" : "WA", "price" : 43, "quantity" : 134, "minimumQuantityForState" : 134 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"), "state" : "WA", "price" : 13, "quantity" : 104, "minimumQuantityForState" : 104 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"), "state" : "WA", "price" : 14, "quantity" : 140, "minimumQuantityForState" : 104 }