Copy an Existing Collection to a New Collection
After a long time, I am writing an article again, this time I will let you know how to copy an existing collection data to a new collection, you can do this in two way.
1. Copy a collection to new collection in mongo shell
First login to mongo shell.
$ mongo MongoDB Enterprise > use demo; switched to db demo MongoDB Enterprise > db demo MongoDB Enterprise > db.collection_name.copy('new_collection_name') ;
Before running the above command you have to make sure the following things.
A. Above command will lock your collection which should be copied to new collection. No Write & Read operations permitted in this collection till .
B. If your existing collection is in production then you must understand no read/write query can come on this collection until the copying of collection completed.
You have to do this on time when traffic will be very low or restore this with mongodump which you have and it won’t have too much impact as it don’t lock read operations if you have replica set. And when you restore with new_collection_name it won’t have any lock as no r/w come to this new_collection.
For more details you can also visit to the below give url:-
2. To copy the collection from dump of collection :-
$ mongodump -d db_name -c collection_name --out directory_name $ cd directory_name/db_name $ mv collection_name.bson new_collection_name.bson $ mv collection_name.metadata.json new_collection_name.metadata.json $ cd ../../ $ mongorestore directory_name
You can check whether new collection has been copied or not in mongo shell.
1. db.collection_name.copy(‘new_collection’); is fast as compare to mongodump and rename and then restoration of collection.
2. db.collection_name.copy(‘new_collection’); will create a r/w lock, so won’t suggest this if existing collection is using production environment. In this situation we should use mongodump and rename the collection and then restore it.
Thanks for going through the article, any suggestions or questions are welcome.