简体   繁体   English

Mongodb findOneAndUpdate() 比较日期和时间戳的总和

[英]Mongodb findOneAndUpdate() compare sums of date and timestamps

I'm working on a MongoDB (+mongoose) based scheduler where tasks have the following type我正在开发基于 MongoDB (+mongoose) 的调度程序,其中任务具有以下类型

TaskSchema {
  running: Boolean
  executedAt: Date,
  next: Number (millisecond)
}

I wish to fetch Tasks which should be executed meaning the sum of executedAt + next < now Since the scheduler should lock the Task, the running flag should be flipped to true in the same operation, hence I'm using findOneAndUpdate() I'm stuck at dealing with the sum of executedAt and next.我希望获取应该执行的任务,这意味着 executeAt executedAt + next < now的总和由于调度程序应该锁定任务, running标志应该在同一操作中翻转为 true,因此我正在使用findOneAndUpdate()我是坚持处理executedAt和next的总和。 How would one compare the sum of these to new Date/Date.now() ?如何将这些总和与new Date/Date.now()进行比较?

When doing an aggregation one could use $dateAdd from what I understand so in a find query could be something.在进行聚合时,可以根据我的理解使用$dateAdd ,因此在查找查询中可能会有所作为。 like the following:如下所示:

    Task.find({
      $and: [
        { running: { $ne: null } },
        { running: false },
        { next: { $ne: null } },
        { executedAt: { $ne: null } },
        {
          $expr: {
            $lt: [
              {
                $dateAdd: {
                  startDate: '$executedAt',
                  unit: 'millisecond',
                  amount: '$next',
                },
              },
              new Date().toUTCString(),
            ],
          },
        },
      ],
    })

However this does not work.但是,这不起作用。

Apparently, my initial attempt works and the above query is nearly correct.显然,我最初的尝试是有效的,上面的查询几乎是正确的。 Since I didn't set the $addDate timezone explicitly I tried making the new Date() a UTC string.由于我没有明确设置$addDate时区,我尝试将new Date()设置为 UTC 字符串。 Considering @Wernfrieds comment this complies to my requirements:考虑到@Wernfrieds 的评论,这符合我的要求:

Task.find({
  $and: [
    { running: { $ne: null } },
    { running: false },
    { next: { $ne: null } },
    { executedAt: { $ne: null } },
    {
      $expr: {
        $lt: [
          {
            $dateAdd: {
              startDate: '$executedAt',
              unit: 'millisecond',
              amount: '$next',
            },
          },
          new Date(),
        ],
      },
    },
  ],
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM