1、单条更新
MongoDB 集合 test1,有字段 _id,createTime,createTimeStr,name字段 , 查询createTime不为空的,根据 _id 生成该条记录的创建时间时间戳并填写到字段 createTime 字段中 ,并打印时间戳
// 查询 createTime 为空的记录
var cursor = db.getCollection("test1").find({"createTime" : null});
while (cursor.hasNext()) {
var doc = cursor.next();
try {
// 提取时间戳部分
var timestamp = doc._id.getTimestamp();
var timestamp2 = Date.parse(timestamp);
// 格式化时间字符串为“yyyyMMdd”
var formattedDate = timestamp.toISOString().slice(0, 10).replace(/-/g, '');
print("Document _id: " + doc._id +" , timestamp2 " + timestamp2 + " , Create Time: " + formattedDate);
db.test1.update(
{ _id: doc._id },
{ $set: { createTime: timestamp2, createTimeStr: formattedDate } }
);
} catch (e) {
// 打印异常信息
print("Error processing document _id: " + doc._id + ". Error: " + e);
// 继续执行下一个文档
continue;
}
}
2、批量更新
var bulkUpdateOps = [];
var batchSize = 1000; // 每批次更新的文档数量
var cursor = db.getCollection("test1").find({ "createTime": null });
cursor.forEach(function (doc) {
try {
var timestamp = doc._id.getTimestamp();
var timestamp2 = Date.parse(timestamp);
var formattedDate = timestamp.toISOString().slice(0, 10).replace(/-/g, '');
bulkUpdateOps.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": {
"createTime": timestamp2,
"createTimeStr": formattedDate
}
}
}
});
// 批量更新达到 batchSize 时执行一次
if (bulkUpdateOps.length === batchSize) {
db.getCollection("test1").bulkWrite(bulkUpdateOps);
bulkUpdateOps = []; // 重置批量更新数组
}
} catch (e) {
print("Error processing document _id: " + doc._id + ". Error: " + e);
// 继续执行下一个文档
}
});
// 处理剩余的批量更新
if (bulkUpdateOps.length > 0) {
db.getCollection("test1").bulkWrite(bulkUpdateOps);
}
代码解释