2015-11-04 73 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 –

相关问题