I want to copy a collection within the same database and give it a different name - basically take a snapshot.
What's the best way to do this? Is there a command, or do I have to copy each record in turn?
I'm aware of the cloneCollection
command, but it seems to be for copying to another server only.
I'm also aware of mongoimport
and mongoexport
, but as I'm doing this via PHP I'd prefer not to make calls out to the shell.
MongoDB – copyTo() Method In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.
In MongoDB, we can combine data of multiple collections into one through the $lookup aggregation stage. In this, you have to specify which collection you want to join with the current collection and select the field that matches in both the collection.
@Naman what is the use case of copy collection, i mean you need any command or it is ok with manually process? for the manual process just install studio3T connect both databases and right click on collection that you want to copy, click on option "Copy Collection" and then go to second database right click on " ...
db.myoriginal.aggregate([ { $match: {} }, { $out: "mycopy" } ])
It is a lot faster than doing many inserts in a forEach loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With