Hi

create a new MongoDB collection with the same indexes as an existing collection

 create a new MongoDB collection with the same indexes as an existing collection


Create an empty collection and copy indexes


Step 1: Create the new collection

db.createCollection("newCollection");


Step 2: Copy all indexes

const indexes = db.oldCollection.getIndexes();


indexes.forEach(index => {

    if (index.name !== "_id_") {

        const { key, name, ...options } = index;

        db.newCollection.createIndex(key, options);

    }

});


This copies all indexes except the default _id index (MongoDB creates that automatically).

Latest
Previous
Next Post »