Skip to content

Instantly share code, notes, and snippets.

@myctw
Created Mar 15, 2022
Embed
What would you like to do?
MongoDB upsert index
/*
Please advise me better coding style and syntax, thanks!
Process Flow:
1. prepare readyToCreateIndexes which contains one or more indexes
2. get all current indexes and compare keyName and key field
- keyName
- not exist:
- fields different, insert!
- fields the same, drop older or ignore new one, depend on your choice
- exist:
- fields different, drop older index and create new one
- fields the same, ignore this index creation
3. drop duplicated indexes and trim non-needed indexes of this creation
4. create index
*/
use somedb;
var Process = {
collectionName: "someCollection",
readyToCreateIndexes: [
{ key: { fieldA: 1, fieldB: 1, fieldC: -1 }, name: "fieldA_1_fieldB_1_fieldC_-1" }
],
getCollection: function() {
let that = this;
return db.getCollection(`${that.collectionName}`);
},
dropIndex: function(toDeletedIndexNames){
let that = this;
print(`\n========== Drop duplicated indexes ============`);
print(`${toDeletedIndexNames}`);
db.runCommand({
dropIndexes: `${that.collectionName}`,
index: toDeletedIndexNames
});
},
createIndex: function(){
let that = this;
print(`\n========== Create indexes ============`);
if (this.readyToCreateIndexes.length == 0) return;
print(`${JSON.stringify(this.readyToCreateIndexes)}`);
db.runCommand({
createIndexes: `${that.collectionName}`,
index: this.readyToCreateIndexes
});
},
getCurrentIndexes: function (){
let that = this;
var bson = this.getCollection().getIndexes();
var json = JSON.stringify(bson);
var obj = JSON.parse(json);
var dict = new Object();
dict = {};
for(var itr = 0 ; itr < obj.length ; itr++)
{
dict[obj[itr].name] = JSON.stringify(obj[itr].key);
}
return dict;
},
getExistedIndexes: function (dict){
let that = this;
var needDeleteIndexes = [];
var spliceIndex = [];
print(`\n========== Skip existed indexes ============`);
for(var itr in this.readyToCreateIndexes){
let createName = this.readyToCreateIndexes[itr].name;
let createKey = JSON.stringify(this.readyToCreateIndexes[itr].key);
for(var keyName in dict){
if (createName == keyName && createKey == dict[keyName]) {
//print(`1. ${createName}, ${createKey}`);
spliceIndex.push(itr);
continue;
}
if (createName == keyName && createKey != dict[keyName]) {
//print(`2. ${createName}, ${createKey}`);
needDeleteIndexes.push(createName);
continue;
}
if (createName != keyName && createKey == dict[keyName]) {
//print(`3. ${createName}, ${createKey}`);
needDeleteIndexes.push(keyName);
continue;
}
}
}
// Remove already existed indexes from create list
let offset = 0;
for(var toSkip in spliceIndex){
toSkip -= offset;
this.readyToCreateIndexes.splice(toSkip,1);
offset++;
}
return needDeleteIndexes;
},
upsertIndex: function(){
let that = this;
// Get current Indexes
let dict = this.getCurrentIndexes();
// Get duplicated with exist index name
var toDeletedIndexNames = this.getExistedIndexes(dict);
// Drop duplicated indexes
this.dropIndex(toDeletedIndexNames);
// Create indexes
this.createIndex();
print(`\n========== reIndex done ============`);
}
};
Process.upsertIndex();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment