Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone a collection in MongoDB

I want to clone a MongoDB collection and save it on the same server with a different name. So for example right now I have the following collections: demo1.categories, demo1.users and demo2.users.

I want to have a "demo2.categories" which is identical to "demo1.categories". (It just has a different name.)

like image 215
Daryna Avatar asked Jan 19 '12 21:01

Daryna


People also ask

How do I copy a collection to another collection in MongoDB?

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 do I copy a collection in MongoDB Atlas?

Paste MongoDB collection Select your target MongoDB database (or collection) that you want to copy your source collection to. In our example, that is database “test” on server “ADX”. Right-click your target and choose Paste Collection.


1 Answers

Yet again the MongoDB documentation comes to the rescue

assuming that the collection actually is named "demo1.categories":

db.demo1.categories.find().forEach( function(x){db.demo2.categories.insert(x)} ); 
like image 186
lhagemann Avatar answered Sep 27 '22 19:09

lhagemann