I have just imported some data from a SQL database into a MongoDB collection and am doing some refactoring. I've just converted a string date value from 'yyyy-mm-dd' format with:
db.Statistic.find({d: {$exists: false}}).forEach(function (x) {
var d = ISODate(x.date);
db.Statistic.update(x, {$set: {"d": d}});
});
which has worked well. Now I want to rebuild the objects with an _id which uses this date so that I don't need a separate date field. I have tried (and many variations):
db.Statistic.find({d: {$exists: true}}).forEach(function (x) {
var oldId = x._id;
x._id = new ObjectId(x.d);
db.Statistic.save(x);
db.Statistic.remove({_id: oldId});
});
but I get Error: invalid object id: length
I assume because the console's ObjectId constructor doesn't accept dates to build a new objectId. Is there any way to do this in the console?