Scroll through the Mongo collection and update the field in each document

I have Dates in one collection that were inserted incorrectly and are in plain format "2015-09-10".

I would like to update them to fix the ISO date format .

I tried iterating through Mongo with forEach(), but I do not know the shell well enough about how to update each document in the collection.

While I am here:

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);
});

What is missing here?

+4
source share
1 answer

The best way to do this is to "Bulk" operations

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();
}
+5
source

Source: https://habr.com/ru/post/1614506/


All Articles