I have a response like this:
"data": [
{
"_id": "6664a8f2f233916895656171",
"workout_plan_id": "6664a5a089450f21a8dd69dc",
"day": "Monday",
"exercise_id": "66643259d020507ed008b16d",
"reps": 15,
"sets": 3,
"created_on": "2024-06-08T18:54:16.287Z",
"updated_on": "2024-06-08T18:54:16.287Z",
"__v": 0
},
{
"_id": "6664aa55ce325f608597f5e8",
"workout_plan_id": "6664a5a089450f21a8dd69dc",
"day": "Monday",
"exercise_id": "66643259d020507ed008b16d",
"reps": 15,
"sets": 3,
"created_on": "2024-06-08T18:59:34.019Z",
"updated_on": "2024-06-08T18:59:34.019Z",
"__v": 0
},
{
"_id": "6664aa89ce325f608597f5eb",
"workout_plan_id": "6664a5a089450f21a8dd69dc",
"day": "Tuesday",
"exercise_id": "66643259d020507ed008b187",
"reps": 15,
"sets": 3,
"created_on": "2024-06-08T18:59:34.019Z",
"updated_on": "2024-06-08T18:59:34.019Z",
"__v": 0
}
]
I want to group the response on the basis of day like this:
monday:[],
tuesday:[],
and so on…
2
Answers
You can achieve the grouping of documents by the weekday directly using MongoDB’s aggregation framework. Here’s how you can do it:
Group by day and accumulate exercises in an array.
Use $project to transform each grouped result into a key-value pair.
Use $group again to accumulate these key-value pairs into an array.
Convert the array to an object using $arrayToObject.
The output looks like:
Option 1:
If doing this in the database you can use an aggregation like so:
See HERE for a working example.
Option 2:
If doing this on the client after your response is received you can use the new Object.groupBy():
For compatability of
Object.groupBy
see Caniuse.