23

I am in the process of changing the schema for one of my MongoDB collections. (I had been storing dates as strings, and now my application stores them as ISODates; I need to go back and change all of the old records to use ISODates as well.) I think I know how to do this using an update, but since this operation will affect tens of thousands of records I'm hesitant to issue an operation that I'm not 100% sure will work. Is there any way to do a "dry run" of an update that will show me, for a small number of records, the original record and how it would be changed?


Edit: I ended up using the approach of adding a new field to each record, and then (after verifying that the data was right) renaming that field to match the original. It looked like this:

db.events.find({timestamp: {$type: 2}})
    .forEach( function (e) {
        e.newTimestamp = new ISODate(e.timestamp);
        db.events.save(e);
    } )

db.events.update({},
    {$rename: {'newTimestamp': 'timestamp'}},
    {multi: true})

By the way, that method for converting the string times to ISODates was what ended up working. (I got the idea from this SO answer.)

4

4 回答 4

6

我的建议是将 ISODate 添加为新字段。一旦确认一切看起来都很好,您就可以取消设置字符串日期。

于 2013-05-17T17:23:14.870 回答
6

使用您的数据库结构创建测试环境。将少量记录复制到其中。问题解决了。我敢肯定,这不是您正在寻找的解决方案。但是,我相信,这是应该使用“测试环境”的确切情况。

于 2013-05-17T13:51:03.393 回答
2

选择您要监控的特定记录的 ID。放在update {_id:{$in:[<your monitored id>]}}

于 2013-05-17T13:52:52.730 回答
0

另一个取决于它将导致您的开销量的选项 - 您可以考虑编写一个脚本,执行查找操作,添加打印输出或在调试中运行,同时注释掉保存操作。一旦您获得信心,您就可以应用保存操作。

 var changesLog = [];
var errorsLog = [];
events.find({timestamp: {$type: 2}}, function (err, events) {
    if (err) {
        debugger;
        throw err;
    } else {
        for (var i = 0; i < events.length; i++) {
            console.log('events' + i +"/"+(candidates.length-1));
            var currentEvent = events[i];
            var shouldUpdateCandidateData = false;

            currentEvent.timestamp = new ISODate(currentEvent.timestamp);


            var change = currentEvent._id;
            changesLog.push(change);

            // // ** Dry Run **
            //     currentEvent.save(function (err) {
            //         if (err) {
            //             debugger;
            //             errorsLog.push(currentEvent._id + ", " + currentEvent.timeStamp + ', ' + err);
            //             throw err;
            //         }
            //     });
        }
        console.log('Done');
        console.log('Changes:');
        console.log(changesLog);
        console.log('Errors:');
        console.log(errorsLog);
        return;
    }
});
于 2017-08-14T14:14:11.030 回答