Necesito obtener el recuento máximo de secuencias negativas de la matriz mediante agregación, documentos de ejemplo:
{ "id": 1, x: [ 1,1,-1,-1,1,1,1,-1,-1,-1,-1] }, { "id": 2, x: [ 1,-1,-1,1,1,1,-1 ] }Resultado Esperado:
{"id": 1,x:4}, {"id": 2,x:2}¿Por favor aconséjame?
Puede usar $reduce para iterar la matriz y $cond para aplicar su lógica (negativos consecutivos)
El transportista está en formato.
{ previous: // previous value to compare for continuity acc: // number of consecutive negatives in the current sequence max: // length of the longest sequence }$let es para memorizar el acumulador actual para reutilizarlo en el cálculo máximo. Es opcional pero conveniente:
db.collection.aggregate([ { "$set": { "x": { "$reduce": { "input": "$x", "initialValue": { previous: 0, acc: 0, max: 0 }, "in": { $let: { vars: { result: { "$cond": { "if": { "$and": [ { "$lt": [ "$$this", 0 ] }, { "$lt": [ "$$value.previous", 0 ] } ] }, "then": { "$add": [ "$$value.acc", 1 ] }, "else": { "$cond": { "if": { "$lt": [ "$$this", 0 ] }, "then": 1, "else": 0 } } } } }, in: { previous: "$$this", acc: "$$result", max: { "$cond": { "if": { $gt: [ "$$value.max", "$$result" ] }, "then": "$$value.max", "else": "$$result" } } } } } } } } }, { "$set": { x: "$x.max" } } ])Pruébalo en mongoplayground.net .
Aquí hay otra forma de hacerlo. La idea general es $reduce la secuencia a una cadena y luego $split para hacer una matriz llena de cadenas de cada ejecución. Luego asigne la matriz de cadenas a una matriz de longitudes de cadena y luego tome el máximo.
db.collection.aggregate({ "$project": { "_id": 0, "id": 1, "x": { "$max": { "$map": { "input": { $split: [ { "$reduce": { "input": "$x", "initialValue": "", "in": { $concat: [ "$$value", { "$cond": [ { "$gt": [ "$$this", 0 ] }, "p", "n" ] } ] } } }, "p" ] }, "in": { "$strLenBytes": "$$this" } } } } } })Pruébalo en mongoplayground.net .