遍历Mongo Collection并更新每个文档中的字段 [英] Loop through Mongo Collection and update a field in every document
本文介绍了遍历Mongo Collection并更新每个文档中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个收藏夹中插入了错误的日期,并且采用了简单的"2015-09-10"
string 格式.
I have Dates in one Collection that were inserted incorrectly, and are in a simple "2015-09-10"
string format.
我想将其更新为正确的 ISO日期格式.
I'd like to update them to correct ISO Date format.
我尝试使用forEach()
遍历Mongo,但是我对如何更新集合中的每个文档的外壳知之甚少.
I've tried looping through Mongo with forEach()
but I don't know the shell well enough on how to update each document in the collection.
到目前为止,我在这里:
So far I'm at this point:
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);
});
这里缺少什么?
推荐答案
最好的方法是使用操作
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();
}
这篇关于遍历Mongo Collection并更新每个文档中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文