2015-11-04 74 views
3

我在一個Collection中的日期插入不正確,並且處於簡單的"2015-09-10"字符串格式。通過Mongo Collection循環收集並更新每個文檔中的字段

我想將它們更新爲正確的ISO日期格式

我試過在Mongo中循環使用forEach(),但是我不知道shell如何更新集合中的每個文檔。

到目前爲止,我在這一點上:

db.getCollection('schedules').find({}).forEach(function (doc) { 

    doc.time = new Date(doc.time).toUTCString(); 

    printjson(doc.time); 
    //^This just prints "Invalid Date" 

    // Also none of the below work when I try saving them 

    //doc.save(); 
    //db.getCollection('schedules').save(doc); 
}); 

缺少了什麼嗎?

回答

4

要做到這一點,最好的辦法是使用"Bulk"操作

var collection = db.getCollection('schedules'); 
var bulkOp = collection.initializeOrderedBulkOp(); 
var count = 0; 
collection.find().forEach(function(doc) { 
    bulkOp.find({ '_id': doc._id }).updateOne({ 
     '$set': { 'time': new Date(doc.time) } 
    }); 
    count++; 
    if(count % 100 === 0) { 
     // Execute per 100 operations and re-init 
     bulkOp.execute(); 
     bulkOp = collection.initializeOrderedBulkOp(); 
    } 
}); 

// Clean up queues 
if(count > 0) { 
    bulkOp.execute(); 
} 
+0

哇謝謝你,所以它比我預想的有點不同。幾乎和貓鼬一樣。 「bulkOp.execute」的目的是批量更新100條記錄嗎? @ user3100115 –

相關問題