I have a collection with items like:
{
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")
}
]
}
Now I need to find all items which had status ACTIVE in May 2020. The array statusHistory contains only dates when status was changed. I need somehow aggregate these array to a form where items contain to date too. Something like:
{
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
}
Then I would like to remove all items out of the period so I want this result:
{
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")
}
]
}
I thought about to use somehow $reduce but I didn't find a solution. It look to me as a common problem in the event sourcing pattern but I am not able to find how to do it.