【问题标题】:Convert BSON ISODate to NumberLong in MongoDB在 MongoDB 中将 BSON ISODate 转换为 NumberLong
【发布时间】:2014-08-16 07:51:01
【问题描述】:

我在 MongoDB 中有一个集合,其中包含 created 字段,其值当前存储为 BSON ISODate 对象。我想将所有这些转换为包含时间戳的 NumberLong 对象。

首先我尝试了这个(在 Mongo shell 中):

db.collection.find( { "created" : { "$type" : 9 } } ).forEach( function (x) {   
  x.created = new NumberLong(x.created);
  db.collection.save(x);
});

JavaScript execution failed: Error: could not convert "Tue Mar 18 2014 18:11:21 GMT-0400 (EDT)" to NumberLong

显然,日期字符串不能被转换为长...足够公平。然后我尝试了这个,认为我可以利用 Javascript Date 对象的 UTC 方法:

db.collection.find( { "created" : { "$type" : 9 } } ).forEach( function (x) {
  x.created = new Date(x.created).UTC();
  db.collection.save(x);
});

JavaScript execution failed: TypeError: Object Tue Mar 18 2014 18:11:21 GMT-0400 (EDT) has no method 'UTC'

我尝试了其他几种变体,但都没有奏效。任何帮助将不胜感激!

【问题讨论】:

    标签: mongodb date timestamp type-conversion bson


    【解决方案1】:

    要访问Date 的底层数值,您可以在其上调用getTime()

    x.created = new NumberLong(x.created.getTime());
    

    【讨论】:

      【解决方案2】:

      ISODate 对象有一个“valueOf”方法,它将返回一个纪元时间。这是一个通过 mongo shell 生成的示例:

      replset:PRIMARY> var date = ISODate()
      replset:PRIMARY> date
      ISODate("2014-06-25T16:31:46.994Z")
      replset:PRIMARY> date.valueOf()
      1403713906994
      replset:PRIMARY> 
      

      【讨论】:

      • 感谢您的回复。 JohnnyHK 打败了你,但你的回答也很有帮助。干杯!
      猜你喜欢
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2017-07-22
      • 2019-01-15
      • 1970-01-01
      • 2022-10-19
      相关资源
      最近更新 更多