按日期分组的 Mongoose 回报

0yg35tkg  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(140)

我的模型如下:

const scheduleTaskSchema = new Schema({
  activity: { type: Object, required: true },
  date: { type: Date, required: true },
  crew: Object,
  vehicle: Object,
  pickups: Array,
  details: String,
});

pickups是具有以下结构的对象数组:

{
time : //iso date,
...rest //irrelevant
}

我想返回按日期分组的数据,并且其中的每个组都必须按pickup[0].time排序,因此它最终将返回类似于以下示例的内容:

{
  "2022-08-28T00:00:00.000+00:00": [
    {
      date: "2022-08-28T00:00:00.000+00:00",
      pickups: [
        {
          time: "2022-08-28T07:30:00.000Z",
          ...rest //irrelevant
        }
      ],
      ...rest //irrelevant
    },
    {
      date: "2022-08-28T00:00:00.000+00:00",
      pickups: [
        {
          time: "2022-08-28T09:30:00.000Z",
          ...rest //irrelevant
        }
      ],
      ...rest //irrelevant
    }
  ]
  ,
   "2022-08-29T00:00:00.000+00:00": [
    {
      date: "2022-08-29T00:00:00.000+00:00",
      pickups: [
        {
          time: "2022-08-29T10:00:00.000Z",
          ...rest //irrelevant
        }
      ],
      ...rest //irrelevant
    },
    {
      date: "2022-08-29T00:00:00.000+00:00",
      pickups: [
        {
          time: "2022-08-29T11:30:00.000Z",
          ...rest //irrelevant
        }
      ],
      ...rest //irrelevant
    }
  ]
}
ev7lccsx

ev7lccsx1#

假设日期完全相同(精确到毫秒),那么代码将如下所示。

const scheduledTasksGroups = await ScheduledTask.aggregate([{
  $group: {
    _id: '$date',
    scheduledTasks: { $push: '$$ROOT' }
  }
}]);

输出将类似于:

[
  { _id: "2022-08-29T10:00:00.000Z", scheduledTasks: [...] },
  { _id: "2022-08-28T10:00:00.000Z", scheduledTasks: [...] }
]

如果要按天分组而不是按毫秒分组,则管道应如下所示:

const scheduledTasksGroups = await ScheduledTask.aggregate([{
  $group: {
    // format date first to `YYYY-MM-DD`, then group by the new format
    _id: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
    scheduledTasks: { $push: '$$ROOT' }
  }
}]);

不管怎么说,这是MongoDB的一个特性,分组发生在MongoDB服务器端; Mongoose 在这里没什么特别的它只是将命令发送给服务器。然后服务器负责将数据分组并返回。
另外,请记住,默认情况下mongoose不会强制转换聚合管道,但this plugin会尽可能自动强制转换mongoose。

相关问题