如何将MongoDB中的属性从文本转换为日期类型?

Jef*_*itz 50 mongodb

在MongoDB中,我有一个带有字段的文档,该字段"ClockInTime"从CSV导入为字符串.

db.ClockTime.update()将这些基于文本的值转换为日期数据类型的适当语句是什么样的?

kri*_*ina 83

这段代码应该这样做:

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

  • @Kristina - Phew,这节省了我很多时间,感谢作者提出这样的问题. (2认同)

Cig*_*ges 15

我和Jeff Fritz的情况完全相同.

就我而言,我已经成功完成了以下更简单的解决方案:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })
Run Code Online (Sandbox Code Playgroud)


Sal*_*til 5

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

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}})
Run Code Online (Sandbox Code Playgroud)

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