Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to copy a collection within the same database?

Tags:

mongodb

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.

like image 578
Tim Avatar asked May 16 '12 19:05

Tim


People also ask

How do you copy a collection in MongoDB of the same database?

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.

How can I combine data from multiple collections into one collection?

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.

How do I copy a collection from one MongoDB to another?

@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 " ...


1 Answers

db.myoriginal.aggregate([ { $match: {} }, { $out: "mycopy" } ]) 

It is a lot faster than doing many inserts in a forEach loop.

like image 98
yoooshi Avatar answered Sep 21 '22 09:09

yoooshi