Comment convertir une propriété dans MongoDB du texte au type de date?

Dans MongoDB, j’ai un document avec un champ appelé "ClockInTime" qui a été importé de CSV sous forme de chaîne.

À quoi ressemble une db.ClockTime.update() appropriée pour convertir ces valeurs textuelles en un type de données de date?

Ce code devrait le faire:

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

J’ai exactement la même situation que Jeff Fritz.

Dans mon cas, j’ai réussi avec la solution plus simple suivante:

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

Ceci est un exemple de code générique en python utilisant 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 ssortingng 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}}) 

pour plus d’informations: http://salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo

Si vous devez vérifier si le champ a déjà été converti, vous pouvez utiliser cette condition:

 /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); } });' 

Sinon, la ligne de commande peut être interrompue.