mongoose 我想更新mongodb中包含datetime字段的对象数组

baubqpgj  于 2023-04-12  发布在  Go
关注(0)|答案(1)|浏览(110)

嗨,我是mongodb的新手,试图更新对象数组中的日期字段。
下面我提到了我的模型,我提到了我的查询,它适用于start_time和end_time,但不更新对象数组,但我需要更新time_slots数组中对象的dateTime字段。
以下是我的mongodb示例文档:

db={
  "teacher": [
    {
      "_id": "6434cf",
      "start_time": ISODate("2023-03-22T07:00:25.787Z"),
      "end_time": ISODate("2023-03-22T10:00:35.604Z"),
      "duration": "15min",
      "time_slots": [
        {
          "sl_no": 1,
          "dateTime": ISODate("2023-03-22T06:30:25.787Z")
        },
        {
          "sl_no": 2,
          "dateTime": ISODate("2023-03-22T06:45:25.787Z")
        }
      ]
    },
    {
      "_id": "6434ctd",
      "start_time": ISODate("2023-03-23T07:00:25.787Z"),
      "end_time": ISODate("2023-03-23T10:00:35.604Z"),
      "duration": "20min",
      "time_slots": [
        {
          "sl_no": 1,
          "dateTime": ISODate("2023-03-23T06:30:25.787Z")
        },
        {
          "sl_no": 2,
          "dateTime": ISODate("2023-03-23T06:50:25.787Z")
        }
      ]
    }
  ]
}

更新start_time和end_time的查询

updateOne(
  { _id:id  },
  [{ 
    $set: {
      start_time: { $dateAdd: { startDate: "$start_time", unit: "minute", amount: hours}},
      end_time: { $dateAdd: { startDate: "$end_time", unit: "minute", amount: hours } }
    }
  }]
)

这是我想要的输出,如果用户想要延迟1小时

{
  "_id": "6434cf" ,
  "start_time":ISODate("2023-03-22T08:00:25.787Z"),
  "end_time":ISODate("2023-03-22T11:00:35.604Z"),
  
  "duration": "15min",
  "time_slots": [
    {
      "sl_no": 1,
      "dateTime": ISODate("2023-03-22T07:30:25.787Z")
    },
    {
      "sl_no": 2 ,
      "dateTime":ISODate("2023-03-22T07:45:25.787Z")
    }
  ],
}

它应该在数组中的start_time、end_time和dateTime字段中增加1小时。

7xllpg7q

7xllpg7q1#

一个选项是使用$map

db.teacher.updateOne(
  {_id: id},
  [
    {$set: {
      start_time: {$dateAdd: {startDate: "$start_time", unit: "minute", amount: delta}},
      end_time: {$dateAdd: {startDate: "$end_time", unit: "minute", amount: delta}},
      time_slots: {$map: {
          input: "$time_slots",
          in: {
            sl_no: "$$this.sl_no",
            dateTime: {$dateAdd: {
                startDate: "$$this.dateTime", unit: "minute", amount: delta
            }}
          }
      }}
    }}
  ]
)

了解它在playground example上的工作原理

相关问题