Skip to content

Instantly share code, notes, and snippets.

@korsmakolnikov
Last active May 2, 2016 11:16
Show Gist options
  • Save korsmakolnikov/d5cd4ce571fa2e1ab4b66689f13fe263 to your computer and use it in GitHub Desktop.
Save korsmakolnikov/d5cd4ce571fa2e1ab4b66689f13fe263 to your computer and use it in GitHub Desktop.
Fix all doctrine autoincrement index of an entire database
var collections = db.getCollectionNames();
//print(collections);
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
collections.forEach(function(col) {
function scan(col) {
try {
var last = db.getCollection(col).find().sort({_id:-1})[0];
var last_increment = db.getCollection('doctrine_increment_ids')
.findOne({'_id':col});
} catch(e) {
print(col + " " + e.message);
}
var item = {};
item['collection'] = col;
item['last_document'] = last['_id'];
item['increment_document'] = !isEmpty(last_increment)?last_increment['current_id']:null;
if(isEmpty(last_increment) && col != 'doctrine_increment_ids' && col != 'system.indexes') {
//fix auto increment inesistente
print('...fixing ' + item['collection']);
var doc = {
'_id': item['collection'],
'current_id': item['last_document']
};
db.getCollection('doctrine_increment_ids')
.insert(doc);
}
if(!isEmpty(last_increment) && col != 'last_imported_id') {
var id_doc = item['last_document'].toString();
var id_increment = item['increment_document'].toString();
if(id_doc !== id_increment) {
//fix incoerenza
print('...fixing ' + item['collection'] + ' where last id should be ' + id_doc + ' but is ' + id_increment + ' instead');
if(typeof item['last_document'] !== 'object') {
item['last_document'] = NumberLong(item['last_document']);
}
db.getCollection('doctrine_increment_ids')
.update({'_id': col}, {'current_id':item['last_document']});
}
}
//print(item);
}
if(col !== 'undefined') {
scan(col);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment