2015-05-26 19 views
1

我有一個包含三百萬個文檔的集合。 每個文檔都有一個「created_at」字段指定字符串格式的時間等這樣 「週四2月5日9時25分38秒+0000 2015年」修改MongoDB中所有文檔的字段時間格式的有效方法

我想改變一切「created_at」字段一個MongoDB支持的時間格式。 所以我寫了一個簡單的Ruby腳本:

collection.find.each do |document| 
    document[:created_at] = Time.parse document[:created_at] 
    collection.save(document) 
end 

它確實改變時間格式,我想,但我的腳本已經運行了50小時,而且沒有整理的跡象。

有沒有更好的方法來完成這項任務? MongoDB shell腳本或Python腳本也適用於我。

順便說一句,這個集合不被索引,因爲它不斷地將文件

+0

難道還有比_id – The6thSense

+0

其他任何唯一的列號這個集合存儲推文數據。即使推特ID也不是唯一的,因爲Twitter API有時會返回重複數據 –

回答

2

使用mongo bulk update您可以更改日期ISODATE如下格式:

var bulk = db.collectionName.initializeOrderedBulkOp(); 
var counter = 0; 
db.collectionName.find().forEach(function(data) { 
    var updoc = { 
     "$set": {} 
    }; 
    var myKey = "created_at"; 
    updoc["$set"][myKey] = new Date(Date.parse(data.created_at)); 
    // queue the update 
    bulk.find({ 
     "_id": data._id 
    }).update(updoc); 
    counter++; 
    // Drain and re-initialize every 1000 update statements 
    if(counter % 1000 == 0) { 
     bulk.execute(); 
     bulk = db.collectionName.initializeOrderedBulkOp(); 
    } 
    }) 
    // Add the rest in the queue 
if(counter % 1000 != 0) bulk.execute(); 
+0

哇,該腳本已準備好使用!我要試試 –

+0

謝謝你這個優雅的腳本! –

+0

@JimGB高興地幫助你:) – Yogesh

相關問題