Created
December 1, 2020 20:52
-
-
Save matiaslopezd/844a8b8c38a11bb7fcbfe436c9eae0c5 to your computer and use it in GitHub Desktop.
Clone all documents of collection to another
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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