MongoDB:将日期字符串(mm / dd / yyyy)转换为Unix时间戳

时间:2016-12-29 22:01:22

标签: mongodb unix-timestamp milliseconds robo3t

只是练习我的MongoDB查询,而且我已经打了一个字段数据类型的墙。

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

我的文档结构如下:

Robomongo Document Structure

是否有MongoDB运算符或方法/方法将当前为mm/dd/yyyy格式的FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("webdriver.log.browser.ignore", true); profile.setPreference("webdriver.log.driver.ignore", true); profile.setPreference("webdriver.log.profiler.ignore", true); FirefoxDriver driver = new FirefoxDriver(); 字段值转换为Unix时间戳,以便我们可以执行过滤操作?

1 个答案:

答案 0 :(得分:0)

您可以迭代所有商品并逐个更新,转换为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时间戳(来自纪元的毫秒),您可以从getTime()致电Date

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"
}])