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.
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' } } } } }, ])