在MongoDB中将BSON ISODate转换为NumberLong

时间:2014-06-25 16:23:05

标签: mongodb date timestamp type-conversion bson

我在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'

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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>