You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:33:20