gpt4 book ai didi

node.js - 循环遍历 Mongo Collection 并更新每个文档中的字段

转载 作者:可可西里 更新时间:2023-11-01 09:11:19 30 4
gpt4 key购买 nike

我在一个集合中有日期插入不正确,并且是简单的 "2015-09-10" string 格式。

我想更新它们以更正 ISO 日期格式

我已经尝试使用 forEach() 遍历 Mongo,但我不太了解 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);
});

这里缺少什么?

最佳答案

最好的方法是使用 "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();
}

关于node.js - 循环遍历 Mongo Collection 并更新每个文档中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33530357/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com