You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何将嵌套字段中的字符串日期转换为ISO日期?

Fixing Nested String Date to ISODate Conversion in MongoDB

Your current script isn’t working because you’re passing the string literal 'data.datetime' directly to ISODate() instead of referencing the actual date value stored in the document. Let’s fix that and optimize the process at the same time.

Corrected Basic Script

var cursor = db.getCollection('log').find({ "data.datetime": { $type: "string" } });
while (cursor.hasNext()) {
    var doc = cursor.next();
    db.log.update(
        { _id: doc._id },
        { $set: { "data.datetime": new ISODate(doc.data.datetime) } }
    );
}

Key Fixes & Improvements:

  • Replaced new ISODate('data.datetime') with new ISODate(doc.data.datetime) to pull the actual string date from the nested field of each document.
  • Added a filter { "data.datetime": { $type: "string" } } to the find() call, so we only process documents where the date is still a string (avoids redundant updates on already converted dates).

Bulk Update for Large Collections

If you’re working with a big dataset, using bulk operations will drastically speed up the process by reducing database round trips:

var bulk = db.log.initializeUnorderedBulkOp();
var batchSize = 1000;
var count = 0;

db.log.find({ "data.datetime": { $type: "string" } }).forEach(function(doc) {
    bulk.find({ _id: doc._id }).updateOne({
        $set: { "data.datetime": new ISODate(doc.data.datetime) }
    });
    count++;
    
    // Execute batch every 1000 documents
    if (count % batchSize === 0) {
        bulk.execute();
        bulk = db.log.initializeUnorderedBulkOp();
    }
});

// Run any remaining operations in the final batch
if (count % batchSize !== 0) {
    bulk.execute();
}

This batch approach ensures you don’t overwhelm the database with too many individual update requests at once.

内容的提问来源于stack exchange,提问作者Gagan Deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:13:28