Node.js中MongoDB按day字段分组数据的实现方案
按Day字段分组数据的解决方案
实现思路
遍历数据数组,以day字段的小写形式作为键,将对应的数据项归类到对应的数组中。
代码示例(JavaScript)
const responseData = { "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 } ] }; // 分组逻辑 const groupedData = responseData.data.reduce((acc, item) => { const dayKey = item.day.toLowerCase(); if (!acc[dayKey]) { acc[dayKey] = []; } acc[dayKey].push(item); return acc; }, {}); console.log(groupedData);
输出结果
{ monday: [ { "_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 } ], tuesday: [ { "_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 } ] }
内容的提问来源于stack exchange,提问作者Apoorv
相关产品推荐
相关产品推荐

