Hi, I tried so long to figure out how to aggregate some documents via a pipeline but I was not able to get close to the result.
I have documents representing zip code ranges belonging to a region and a “last delivery date” for each range of zip codes. I would like to obtain one document for each contiguous range belonging to a region, with the date of the last delivery that happened for that range.
Currently I am doing it programmatically in my app, but doing that with an aggregation would bring to a major performance improvement given that it is much more efficient to don’t have to process all the documents on the client side.
Here a sample of my dataset:
[
{
region: "EMEA",
startZipCode: 0,
endZipCode: 10,
lastDelivery: ISODate("2020-01-01T10:58:18Z")
},
{
region: "EMEA",
startZipCode: 10,
endZipCode: 20,
lastDelivery: ISODate("2020-12-01T11:13:26Z")
},
{
region: "EMEA",
startZipCode: 20,
endZipCode: 30,
lastDelivery: ISODate("2020-11-01T11:13:26Z")
},
{
region: "NA",
startZipCode: 30,
endZipCode: 40,
lastDelivery: ISODate("2020-01-01T11:13:26Z")
},
{
region: "NA",
startZipCode: 40,
endZipCode: 50,
lastDelivery: ISODate("2020-01-01T11:13:26Z")
},
{
region: "EMEA",
startZipCode: 50,
endZipCode: 60,
lastDelivery: ISODate("2020-01-01T11:13:26Z")
}
]
Here an example of the output I would expect:
// Range [0-30) belonging to EMEA
// Grouping together contiguous zip codes (3 first docs)
// And choosing the higher delivery date in the group
{
region: "EMEA",
startZipCode: 0,
endZipCode: 30,
lastDelivery: ISODate("2020-12-01T11:13:26Z")
},
// Range [30, 50) belonging to NA
// Grouping together contiguous zip codes (2 docs)
// And choosing the higher delivery date in the group (they're the same)
{
region: "NA",
startZipCode: 30,
endZipCode: 50,
lastDelivery: ISODate("2020-01-01T11:13:26Z")
},
// Range [50, 60) belonging to EMEA (single document in the range, no grouping needed)
{
region: "EMEA",
startZipCode: 50,
endZipCode: 60,
lastDelivery: ISODate("2020-01-01T11:13:26Z")
}
Thank you very much in advance for your help.