Below is my document. I want to compare the objects in array SKUPromo and get only those objects which have overlapping dates.
{
"_id": "2531090",
"SKUPromo": [
{
"_id": "1",
"startDateTime": {
"$date": "2023-01-05T06:00:00.000Z"
},
"endDateTime": {
"$date": "2023-02-07T05:59:59.000Z"
},
"promotionID": "6262",
"skuId": "2531090"
},
{
"_id": "2",
"startDateTime": {
"$date": "2023-06-25T05:00:00.000Z"
},
"endDateTime": {
"$date": "2023-07-16T04:59:59.000Z"
},
"promotionID": "10146",
"skuId": "2531090"
},
{
"_id": "3",
"startDateTime": {
"$date": "2023-06-25T05:00:00.000Z"
},
"endDateTime": {
"$date": "2023-07-02T04:59:59.000Z"
},
"promotionID": "8749",
"skuId": "2531090"
},
{
"_id": "4",
"startDateTime": {
"$date": "2023-06-04T05:00:00.000Z"
}
"endDateTime": {
"$date": "2023-06-11T04:59:59.000Z"
},
"promotionID": "10024",
"skuId": "2531090"
},
{
"_id": "5",
"startDateTime": {
"$date": "2023-01-01T06:00:00.000Z"
},
"endDateTime": {
"$date": "2023-01-07T05:59:59.000Z"
},
"promotionID": "6262",
"skuId": "2531090"
}
]
}
The output should have below data,
{
"_id": "2531090",
"SKUPromo": [
{
"_id": "1",
"startDateTime": {
"$date": "2023-01-05T06:00:00.000Z"
},
"endDateTime": {
"$date": "2023-02-07T05:59:59.000Z"
},
"promotionID": "9345",
"skuId": "2531090"
},
{
"_id": "2",
"startDateTime": {
"$date": "2023-06-25T05:00:00.000Z"
},
"endDateTime": {
"$date": "2023-07-16T04:59:59.000Z"
},
"promotionID": "10146",
"skuId": "2531090"
},
{
"_id": "3",
"startDateTime": {
"$date": "2023-06-25T05:00:00.000Z"
},
"endDateTime": {
"$date": "2023-07-02T04:59:59.000Z"
},
"promotionID": "8749",
"skuId": "2531090"
},
{
"_id": "5",
"startDateTime": {
"$date": "2023-01-01T06:00:00.000Z"
},
"endDateTime": {
"$date": "2023-01-07T05:59:59.000Z"
},
"promotionID": "6262",
"skuId": "2531090"
}
]
}
2
Answers
This may not be exactly what the OP is looking for but the challenge of iterating over a list and examining each element in the context of the rest of the list is a good one. Here’s a potential solution:
This yields:
Here’s one way you could do it using
"$reduce"
. Comments are in the aggregation pipeline.Try it on mongoplayground.net.