我试图在所有文档中基于另一个字段插入一个新字段。目前,我有近3.3亿份文件。一张一张地更新要花费很多时间。下面是我的示例代码,
var db = connect('127.0.0.1:27017/sampleDatabase');
print('Database connect');
collectionsList = [1 .... 100];
collectionsList.forEach(addNewTimeField);
function addNewTimeField(value, index, array){
let collectionName = 'name_' + value;
db[collectionName].find().forEach(function(doc) {
db[collectionName].update({_id:doc._id}, {$set:{"ts": new Date(doc.timeStamp)}});
});
db[collectionName].createIndex({ "ts" : 1 }, { expireAfterSeconds: 31622400 }, { "background": true} );
}
有没有一种方法可以使用批量更新同时更新多个记录?提前致谢。
您可以尝试使用MongoDB v4.2中的聚合管道进行更新,
db[collectionName].updateMany(
{},
[{
$set: { ts: { $toDate: "$timeStamp" } }
}]
);
第二个选项是bulkWrite(),它将更新单个事务中的所有记录,
async function addNewTimeField(value, index, array){
let collectionName = 'name_' + value;
let allDocs = await db[collectionName].find({}, { timeStamp: 1 });
let updateAllDocs = allDocs.map(({ _id, timeStamp }) => ({
updateOne: {
filter: { _id: ObjectId(_id) },
update: { ts: new Date(timeStamp) }
}
}));
db[collectionName].bulkWrite(updateAllDocs);
db[collectionName].createIndex({ "ts" : 1 }, { expireAfterSeconds: 31622400 }, { "background": true} );
}
未经测试而准备好的bulkWrite查询,如果遇到任何问题,请通知我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句