Created
October 7, 2013 08:02
-
-
Save salilpa/6864117 to your computer and use it in GitHub Desktop.
Sample Python script to convert a property in MongoDB from text to date type using pymongo. This script finds all documents which has to be changed and changes it one by one using the id attribute.
more info at http://salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment