We need to iterate over the snapshot()
of our documents and update each document using the $set
update operator. And to do this we use bulk operation for maximum efficiency.
Starting from MongoDB 3.2, we need to use the bulkWrite()
method
var requests = [];
let cursor = db.collection.find({}, { "Profession_id": 1 }).snapshot();
cursor.forEach( document => {
requests.push( {
"updateOne": {
"filter": { "_id": document._id },
"update": { "$set": { "Profession_id": ObjectId(document.Profession_id) } }
}
});
if (requests.length === 1000) {
// Execute per 1000 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
// Clean up queues
if (requests.length > 0)
db.collection.bulkWrite(requests);
From MongoDB 2.6 to 3.0 you need to use the now deprecated Bulk
API and it associated method.
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
var cursor = db.collection.find({}, { "Profession_id": 1 }).snapshot()
cursor.forEach(function(document) {
bulk.find( { "_id": document._id } ).updateOne( {
"$set: { "Profession_id": ObjectId(document.Profession_id) }
} );
count++;
if (count % 1000 === 0) {
// Execute per 1000 operations and re-init
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
}
});
// Clean up queues
if (count > 0)
bulk.execute();
let cursor = db.collection.find({ "TheString_id" : { $type : "string" } }, { "TheString_id": 1 }).snapshot();
to avoid some errors on partial updates – Meehan