Skip to content

Instantly share code, notes, and snippets.

@sreevardhanreddi
Created April 29, 2023 05:41
Show Gist options
  • Save sreevardhanreddi/0e2d2b45020d50703cf617cd6665cb93 to your computer and use it in GitHub Desktop.
Save sreevardhanreddi/0e2d2b45020d50703cf617cd6665cb93 to your computer and use it in GitHub Desktop.
a script to sync mongodb indexes
require("dotenv").config();
const mongoClient = require("mongodb").MongoClient;
const MONGO_DB_SRC =
process.env.MONGO_DB_SRC || "mongodb://localhost:27017/db1";
const MONGO_DB_DEST =
process.env.MONGO_DB_DEST || "mongodb://localhost:27017/db2";
const syncIndexes = async () => {
try {
console.log("Fetching indexes from source ...");
const client = await mongoClient.connect(MONGO_DB_SRC, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const collections = await db.listCollections().toArray();
const collectionNames = collections.map((collection) => collection.name);
let results = await Promise.allSettled(
collectionNames.map(async (collectionName) => {
let indexList = [];
let indexes = await db.collection(collectionName).indexes();
indexes.forEach((index) => {
delete index.v;
delete index.ns;
let key = index.key;
delete index.key;
let options = {};
for (let opt in index) {
options[opt] = index[opt];
}
indexList.push({ key: key, options: options });
});
return {
collectionName: collectionName,
indexes: indexList,
};
})
);
results
.filter((result) => result.status === "rejected")
.forEach((result) => {
console.error(result.reason.message);
console.log("-".repeat(50));
});
results = results.filter((result) => result.status === "fulfilled");
let indexes = results.map((result) => result.value);
console.log("Indexes fetched successfully.");
console.log("list of indexes ");
indexes.map((index) => console.log(JSON.stringify(index)));
console.log("Syncing indexes to destination ...");
const clientDest = await mongoClient.connect(MONGO_DB_DEST, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const dbDest = clientDest.db();
await Promise.allSettled(
indexes.map(async (index) => {
let indexList = index.indexes || [];
return await Promise.allSettled(
indexList.map(async (indexObj) => {
try {
console.log(
"Syncing index",
JSON.stringify(indexObj),
"for collection",
index.collectionName,
"..."
);
return await dbDest
.collection(index.collectionName)
.createIndex(indexObj.key, indexObj.options);
} catch (error) {
console.log(error);
}
})
);
})
);
console.log("Indexes synced successfully");
process.exit(0);
} catch (err) {
console.log(err);
process.exit(1);
}
};
const main = async () => {
await syncIndexes();
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment