2012-06-08 117 views
15

有没有办法使用MongoDB的外壳采用自定义格式字符串转换为日期MongoDB中转换字符串到日期

我试图转换“21 /月/ 2012:16:35:33 -0400”至今,

有没有办法通过DateFormatter什么的到 Date.parse(...)ISODate(....)方法?

+0

的http:// developwithstyle。 com/articles/2010/07/09/handling-dates-in-mongodb /,不完全是你想要的,但你仍然可以看看 –

+0

http://stackoverflow.com/questions/2900674/how-doi-i-从文本到日期类型转换为MongoDB中的属性,也可以看看这个 –

回答

4

您可以在由Ravi Khakhkhar提供的第二个链接中使用JavaScript,或者您将不得不执行一些字符串操作来转换您的原始字符串(因为原始格式中的某些特殊字符未被识别为有效的定界符),但是一旦你做到这一点,你可以用“新”

training:PRIMARY> Date() 
Fri Jun 08 2012 13:53:03 GMT+0100 (IST) 
training:PRIMARY> new Date() 
ISODate("2012-06-08T12:53:06.831Z") 

training:PRIMARY> var start = new Date("21/May/2012:16:35:33 -0400")  => doesn't work 
training:PRIMARY> start 
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ") 

training:PRIMARY> var start = new Date("21 May 2012:16:35:33 -0400")  => doesn't work  
training:PRIMARY> start 
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ") 

training:PRIMARY> var start = new Date("21 May 2012 16:35:33 -0400")  => works 
training:PRIMARY> start 
ISODate("2012-05-21T20:35:33Z") 

下面是一些链接,你可以蒙戈外壳内发现有用的(有关数据的修改) -

http://cookbook.mongodb.org/patterns/date_range/

http://www.mongodb.org/display/DOCS/Dates

http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell

+1

谢谢。我用外部客户端重新加载数据 - http://stackoverflow.com/questions/6154594/how-do-you-store-a-string-in-mongodb-as-a-date-type-using-ruby?rq= 1 – user883257

+1

很酷,谢谢你让我知道。如果你觉得我的答案是有帮助的,你能否也请你放心吗? –

27

在我的情况我有以下解决方案成功从字符串从ClockTime收集转换领域ClockInTime为Date类型

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime); 
    db.ClockTime.save(doc); 
    }) 
+5

我使用了''新的ISODate(...)'作为我的日期字符串,并且工作完美。感谢您的建议。 – sumitkm

+0

'新日期(...)'搞砸了我的日期。 '新的ISODate(...)'工作。谢谢@sumitkm – Tur1ng

+1

我不知道为什么,但这种方法需要比var cursor = db.restaurant_review.find()等更长的时间来执行。 (cursor.hasNext()){ var doc = cursor.next(); db.restaurant_review.update({_ id:doc._id},{$ set:{date:new ISODate(doc.date)}}) }; – qwerty123

3

我在MongoDB的一些字符串必须将它们重新格式化为MongoDB中正确且有效的dateTime字段。

,这里是我的特殊日期格式代码:“2014-03-12T09:14:19.5303017 + 01:00”

,但你可以采取easyly这个想法,写自己的正则表达式来解析日期格式:

// format: "2014-03-12T09:14:19.5303017+01:00" 
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/; 

db.Product.find().forEach(function(doc) { 
    var matches = myregexp.exec(doc.metadata.insertTime); 

    if myregexp.test(doc.metadata.insertTime)) { 
     var offset = matches[9] * (matches[8] == "+" ? 1 : -1); 
     var hours = matches[4]-(-offset)+1 
     var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7]/10000.0) 
     db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}}) 
     print("succsessfully updated"); 
    } else { 
     print("not updated"); 
    } 
}) 
8

做转换,就需要使用forEach()方法 或光标方法,通过两种手动循环由find()方法返回游标next()访问文档。 Withing环路,场转换为ISODate对象,然后使用$set操作员更新的字段,如下面的例子,其中字段被称为created_at,目前持有以字符串格式的日期:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    db.collection.update(
     {"_id" : doc._id}, 
     {"$set" : {"created_at" : new ISODate(doc.created_at)}} 
    ) 
}; 

为了提高性能,特别是在处理大型集合时,请利用批量更新使用,因为您将批量发送操作到服务器1000,这样可以提供更好的性能,因为您不会将每个请求发送到服务器,每1000个请求中只有一次。

以下演示了这种方法,第一个示例使用MongoDB版本>= 2.6 and < 3.2中提供的Bulk API。它通过改变created_at字段日期字段更新集合中的所有 文件:

var bulk = db.collection.initializeUnorderedBulkOp(), 
    counter = 0; 

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at); 
    bulk.find({ "_id": doc._id }).updateOne({ 
     "$set": { "created_at": newDate} 
    }); 

    counter++; 
    if (counter % 1000 == 0) { 
     bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements 
     bulk = db.collection.initializeUnorderedBulkOp(); 
    } 
}) 
// Clean up remaining operations in queue 
if (counter % 1000 != 0) { bulk.execute(); } 

下一个例子适用于新的MongoDB版本3.2提供一种具有自deprecated the Bulk API和使用API的新集bulkWrite()

var bulkOps = [], 
    cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 

cursor.forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at); 
    bulkOps.push(   
     { 
      "updateOne": { 
       "filter": { "_id": doc._id } ,    
       "update": { "$set": { "created_at": newDate } } 
      }   
     }   
    ); 

    if (bulkOps.length === 500) { 
     db.collection.bulkWrite(bulkOps); 
     bulkOps = []; 
    }  
}); 

if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps); 
0

如何使用像momentjs库通过写这样的脚本:

[install_moment.js] 
function get_moment(){ 
    // shim to get UMD module to load as CommonJS 
    var module = {exports:{}}; 

    /* 
    copy your favorite UMD module (i.e. moment.js) here 
    */ 

    return module.exports 
} 
//load the module generator into the stored procedures: 
db.system.js.save({ 
     _id:"get_moment", 
     value: get_moment, 
    }); 

然后在命令行加载脚本像这样:

> mongo install_moment.js 

最后,在你的下一个蒙戈会议,使用它像这样:

// LOAD STORED PROCEDURES 
db.loadServerScripts(); 

// GET THE MOMENT MODULE 
var moment = get_moment(); 

// parse a date-time string 
var a = moment("23 Feb 1997 at 3:23 pm","DD MMM YYYY [at] hh:mm a"); 

// reformat the string as you wish: 
a.format("[The] DDD['th day of] YYYY"): //"The 54'th day of 1997"