我在MongoDB中有一个集合,其中包含创建的
字段,其值当前存储为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'
我已经尝试了其他几种变体,但还没有成功。任何帮助都将不胜感激!
要访问Date
的底层数值,您可以在其上调用getTime()
:
x.created = new NumberLong(x.created.getTime());
ISODate对象有一个"value eOf"方法,该方法将返回一个纪元时间。下面是一个通过shell生成mongo示例:
replset:PRIMARY> var date = ISODate()
replset:PRIMARY> date
ISODate("2014-06-25T16:31:46.994Z")
replset:PRIMARY> date.valueOf()
1403713906994
replset:PRIMARY>