如何将文本中的MongoDB属性转换为datetypes?

在MongoDB中,我有一个名为"ClockInTime"的字段,它是从CSV导入的string。

什么适当的db.ClockTime.update()语句看起来像将这些基于文本的值转换为date数据types?

这段代码应该这样做:

 > var cursor = db.ClockTime.find() > while (cursor.hasNext()) { ... var doc = cursor.next(); ... db.ClockTime.update({_id : doc._id}, {$set : {ClockInTime : new Date(doc.ClockInTime)}}) ... } 

我和Jeff Fritz的情况完全一样。

在我的情况下,我已经成功了以下更简单的解决scheme:

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

这是Python中使用pymongo的通用示例代码

 from pymongo import MongoClient from datetime import datetime def fixTime(host, port, database, collection, attr, date_format): #host is where the mongodb is hosted eg: "localhost" #port is the mongodb port eg: 27017 #database is the name of database eg : "test" #collection is the name of collection eg : "test_collection" #attr is the column name which needs to be modified #date_format is the format of the string eg : "%Y-%m-%d %H:%M:%S.%f" #http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior client = MongoClient(host, port) db = client[database] col = db[collection] for obj in col.find(): if obj[attr]: if type(obj[attr]) is not datetime: time = datetime.strptime(obj[attr],date_format) col.update({'_id':obj['_id']},{'$set':{attr : time}}) 

更多信息: http : //salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo

如果您需要检查该字段是否已被转换,则可以使用以下条件:

 /usr/bin/mongo mydb --eval 'db.mycollection.find().forEach(function(doc){ if (doc.date instanceof Date !== true) { doc.date = new ISODate(doc.date); db.mycollection.save(doc); } });' 

否则命令行可能会中断。