53 votes

Comment puis-je convertir une propriété dans MongoDB à partir de texte de type date?

Dans MongoDB, j'ai un document avec un champ appelé "ClockInTime" qui a été importé à partir d'un fichier CSV comme une chaîne de caractères.

Qu'est-ce qui décibels.ClockTime.mise à jour() déclaration de ressembler à convertir le texte en fonction des valeurs d'un type de données de date?

86voto

kristina Points 7269

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)}})
... }

15voto

Ciges Points 320

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

Dans mon cas, j'ai réussi à la suite de solution plus simple:

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

5voto

C'est un exemple générique de code en python à l'aide de 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}})

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

1voto

webDEVILopers Points 374

Si vous avez besoin de vérifier si le champ a déjà été convertis, 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 se briser.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X