【问题标题】:Regex in Mongodb for ISO Date fieldMongodb中ISO日期字段的正则表达式
【发布时间】:2021-03-21 00:54:01
【问题描述】:

尽管有日期值,我如何才能选择时间值为 00:00:00 的所有日期?正则表达式对我不起作用。

{
    "_id" : ObjectId("59115a92bbf6401d4455eb21"),
    "name" : "sfdfsdfsf",
    "create_date" : ISODate("2013-05-13T02:34:23.000Z"),
}

类似:

db.myCollection.find({"create_date": /*T00:00:00.000Z/ })

【问题讨论】:

  • 给我否决票的理由。我在stackoverflow上找不到解决方案。并且提供的解决方案对我不起作用。你有什么理由投反对票吗?
  • 不确定这是否适合您,但您可以使用聚合来做到这一点
  • 我的要求是找到创建时间为 00:00:00 的所有记录(从日期和时间的组合)并更新它们。即使是聚合,我也需要找到一种方法来选择这些记录。正则表达式似乎是解决方案,但没有什么对我有用。

标签: regex mongodb


【解决方案1】:

您需要先将创建日期转换为时间字符串,如果时间为00:00:00:000,则包含该文档。

db.test.aggregate([
  // Part 1: Project all fields and add timeCriteria field that contain only time(will be used to match 00:00:00:000 time)
  {
    $project: {
      _id: 1,
      name: "$name",
      create_date: "$create_date",
      timeCriteria: {
        $dateToString: {
          format: "%H:%M:%S:%L",
          date: "$create_date"
        }
      }
    }
  },
  // Part 2: match the time
  {
    $match: {
      timeCriteria: {
        $eq: "00:00:00:000"
      }
    }
  },
  // Part 3: re-project document, to exclude timeCriteria field.
  {
    $project: {
      _id: 1,
      name: "$name",
      create_date: "$create_date"
    }
  }
]);

【讨论】:

    【解决方案2】:

    从 MongoDB 版本 >= 4.4 开始,我们可以使用 $function 运算符编写自定义过滤器。

    注意:不要忘记将时区更改为您的要求。时区不是强制性的。

    let timeRegex = /.*T00:00:00.000Z$/i;
    
    db.myCollection.find({
      $expr: {
        $function: {
          body: function (createDate, timeRegex) {
            return timeRegex.test(createDate);
          },
          args: [{ $dateToString: { date: "$create_date", timezone: "+0530" } }, timeRegex],
          lang: "js"
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2014-10-11
      • 1970-01-01
      • 2012-12-17
      • 2020-08-11
      • 1970-01-01
      • 2013-10-23
      相关资源
      最近更新 更多