Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
la agregación mongodb obtiene el número máximo de secuencias negativas en la matriz

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 .

over 4 years ago · Santiago Trujillo Report

0

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 .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!