【问题标题】:MongoDB: Convert Date String (mm/dd/yyyy) to Unix timestampMongoDB:将日期字符串 (mm/dd/yyyy) 转换为 Unix 时间戳
【发布时间】:2018-01-31 03:45:31
【问题描述】:

刚刚练习了我的 MongoDB 查询,但我遇到了字段数据类型的问题。

我目前使用 Robomongo 作为 GUI 来访问生产数据库。

我的文档结构如下:

是否有 MongoDB 运算符或方式/方法将当前为 mm/dd/yyyy 格式的 date 字段值转换为 Unix 时间戳,以便我们可以执行过滤操作?

【问题讨论】:

    标签: mongodb unix-timestamp milliseconds robo3t


    【解决方案1】:

    您可以迭代所有项目并通过转换为Date 进行一项一项更新。这是一个将您的日期从 mm/dd/yyyy 转换为 ISODate 的示例:

    db.test.find().forEach( function(res){
    
          if (typeof(res.date)=="string"){
            var arr = res.date.split("/");
            res.date = new Date(arr[2], arr[0] - 1, arr[1]);
            db.test.save(res)
          }
        }
    )
    

    对于 Unix 时间戳(来自纪元的毫秒),您可以从 Date 调用 getTime()

    db.test.find().forEach( function(res){
    
          if (typeof(res.date)=="string"){
            var arr = res.date.split("/");
            res.date = new Date(arr[2], arr[0] - 1, arr[1]).getTime();
            db.test.save(res)
          }
        }
    )
    

    请注意,这些日期将被转换为 UTC 格式,因此您可能需要在进行转换之前临时更改您的时区

    如果你想优化更新性能,也可以使用bulk update

    您也可以将日期转换为yyyy-mm-dd,这将保留排序(检查this post)。以下会将您的日期字段分解为daymonthyear,使用新格式设置日期字段并将输出写入名为test2 的新集合中:

    db.test.aggregate([{
        $project: {
            startTime: 1,
            endTime: 1,
            date: {
                $let: {
                    vars: {
                        year: { $substr: ["$date", 6, 10] },
                        month: { $substr: ["$date", 0, 2] },
                        dayOfMonth: { $substr: ["$date", 3, 2] }
                    },
                    in : { $concat: ["$$year", "-", "$$month", "-", "$$dayOfMonth"] }
                }
            }
        }
    },{
        $out :"test2"
    }])
    

    【讨论】:

    • 感谢@BertrandMartel。这真的很有帮助,但是我希望将其保留在 MongoDB 中,因为这是聚合查询的一部分。如果一切可能,我希望避免使用 Javascript、PHP 等进行转换。是否有使用各种 MongoDB 运算符来实现此目的的流程?
    • 我已经更新了我的帖子,将你的字符串日期格式转换为yyyy-mm-dd,这不是你想要的,但与mm-dd-yyyy相比会保留排序
    猜你喜欢
    • 2021-03-11
    • 2022-08-03
    • 1970-01-01
    • 2018-05-19
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    相关资源
    最近更新 更多