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

175
Views
Cómo obtener todos los elementos que coinciden con la condición en el período de tiempo en una matriz que contiene solo desde la fecha en Mongodb

Tengo una colección con artículos como:

 { id: 1, statusHistory: [ { status: "ACTIVE", date: ISODate("2020-04-26T22:02:26.000Z") }, { status: "DISABLED", date: ISODate("2020-05-20T22:02:26.000Z") } ] } { id: 2, statusHistory: [ { status: "ACTIVE", date: ISODate("2020-05-26T22:02:26.000Z") } ] } { id: 3, statusHistory: [ { status: "ACTIVE", date: ISODate("2020-04-26T22:02:26.000Z") }, { status: "DISABLED", date: ISODate("2020-04-27T22:02:26.000Z") } ] }

Ahora necesito encontrar todos los elementos que tenían el estado ACTIVO en mayo de 2020. La matriz statusHistory contiene solo las fechas en las que se cambió el estado. Necesito de alguna manera agregar esta matriz a un formulario donde los elementos también contengan hasta la fecha. Algo como:

 { status: "ACTIVE", date: ISODate("2020-04-26T22:02:26.000Z"), // from dateTo: ISODate("2020-05-20T22:02:26.000Z") // it is from the date of the next item in the array }

Luego, me gustaría eliminar todos los elementos del período, así que quiero este resultado:

 { id: 1, statusHistory: [ { status: "ACTIVE", date: ISODate("2020-04-26T22:02:26.000Z") } ] } { id: 2, statusHistory: [ { status: "ACTIVE", date: ISODate("2020-05-26T22:02:26.000Z") } ] }

Pensé en usar de alguna manera $reduce pero no encontré una solución. Me parece un problema común en el patrón de abastecimiento de eventos, pero no puedo encontrar cómo hacerlo.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

La siguiente canalización puede no ser la mejor, pero vale la pena intentarlo. Lo actualizará con algunas explicaciones, pero para ayudar a comprender la canalización o para depurarla en caso de que obtenga resultados inesperados, ejecute la agregación con solo el primer paso de la canalización. Por ejemplo, ejecute la agregación en mongo Shell como:

 db.collection.aggregate([ { '$addFields': { .... } } ])

Verifique el resultado para ver si la nueva matriz statusHistory se construye correctamente con un nuevo campo dateTo . Si eso da el resultado esperado, agregue lo siguiente:

 db.collection.aggregate([ { '$addFields': { .... } }, { '$match': { ... } } ])

Entonces, en general, ejecute la operación

 db.collection.aggregate([ { '$addFields': { 'statusHistory': { '$map': { 'input': '$statusHistory', 'in': { '$mergeObjects': [ '$$this', { 'dateTo': { '$arrayElemAt': [ '$statusHistory', { '$indexOfArray': [ '$statusHistory.status', 'DISABLED' ] } ] } } ] } } } } }, { '$match': { '$expr': { '$gt': [ { '$size': { '$filter': { 'input': '$statusHistory', 'cond': { '$and': [ { '$eq': ['$$this.status', 'ACTIVE'] }, { '$gte': ['$$this.dateTo.date', new Date('2020-05-01')] } ] } } } }, 0 ] } } }, { '$addFields': { 'statusHistory': { '$map': { 'input': { '$filter': { 'input': '$statusHistory', 'as': 'item', 'cond': { '$eq': ['$$item.status', 'ACTIVE'] } } }, 'in': { 'status': '$$this.status', 'date': '$$this.date' } } } } }, ])
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!