Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Created December 1, 2020 20:52
Show Gist options
  • Save matiaslopezd/844a8b8c38a11bb7fcbfe436c9eae0c5 to your computer and use it in GitHub Desktop.
Save matiaslopezd/844a8b8c38a11bb7fcbfe436c9eae0c5 to your computer and use it in GitHub Desktop.
Clone all documents of collection to another
/**
* Get all documents of collection
* @param db {Object} - MongoDB connection
* @param collectionName {String} - Collection name
* @returns {Promise<Array>}
*/
async function getDocs(db, collectionName) {
const collection = db.collection(collectionName);
const cursor = await collection.find();
return cursor.toArray();
}
/**
* Clone all documents collection to another
* @param db {Object} - MongoDB connection
* @param originalCollection {String} - The original collection
* @param destinationCollection {String} - The destination collection
* @returns {Promise<*>}
*/
async function cloneCollection(db, originalCollection, destinationCollection) {
const docs = await getDocs(db, originalCollection);
return db.collection(destinationCollection).insertMany(docs); // Check here for errors: https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment