I have json data like this:
[{
"Id": 1,
"Name": "Test 1",
"Time": {
"start": "22:00",
"end": "22:30",
"duration": 30
}
}, {
"Id": 2,
"Name": "Test 2",
"Time": {
"start": "22:05",
"end": "22:35",
"duration": 30
}
}, {
"Id": 3,
"Name": "Test 3",
"Time": {
"start": "23:25",
"end": "23:40",
"duration": 15
}
},{
"Id": 4,
"Name": "Test 4",
"Time": {
"start": "22:15",
"end": "22:50",
"duration": 15
}
}
]
And i want get result like this, determine which intersect by Time:
[
["Test 1", "Test 2", "Test 4"],
["Test 3"]
]
I have solution, but it's too complicated and i use 4 loops inside each other
If there is an easier solution, please suggest, thanks!
Try aggregation, I am not sure this will work exact as per your requirement,
$addFields add new field startHour, that splits string hour and minute from string, using $split, and $arrayElemAt return first element means hour$group by startHour and make array of Namedb.collection.aggregate([
{
$addFields: {
startHour: {
$arrayElemAt: [{ $split: ["$Time.start", ":"] }, 0]
}
}
},
{
$group: {
_id: "$startHour",
Name: { $push: "$Name" }
}
}
])
Result:
[
{
"Name": ["Test 1","Test 2","Test 4"],
"_id": "22"
},
{
"Name": ["Test 3"],
"_id": "23"
}
]