2015-05-26 21 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

相关问题