Clone a collection in MongoDB

I want to clone a MongoDB collection and store 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 "demo2.categories" which is identical to "demo1.categories". (He just has a different name.)

+44
mongodb
Jan 19 '12 at 21:08
source share
7 answers

And again the MongoDB document comes to the rescue

assuming the collection is actually called "demo1.categories":

db.demo1.categories.find().forEach( function(x){db.demo2.categories.insert(x)} ); 
+75
Jan 19 '12 at 21:45
source share
— -

The easiest and most efficient way is to use copyTo () so you can use:

 db.source.copyTo("target"); 

& if "target" does not exist, it will be created

- Update -

According to CopyTo Documentation , since copyTo() uses eval internally, copy operations will block all other operations on the mongod instance. Therefore, it cannot be used in a production environment.

- Update -

Since copyTo() uses eval() internally, and eval() deprecated since version 3.0, so copyTo() also deprecated since version 3.0.

+28
Jan 19 '14 at 17:43
source share

This is the fastest way to clone your collection:

 mongoexport -d db_name -c src_collection | mongoimport -d db_name -c dst_collection --drop 

it will clone src_collection to db_name before dst_collection . Or you can do this in two steps at the bson level:

 mongodump -d db_name -c src_collection mongorestore --drop -d db_name -c dst_collection ./dump/db_name/src_collection.bson 
+18
Jul 25 '14 at 21:31
source share

The fastest option is

 db.myoriginal.aggregate([ { $out: "mycopy" } ]) 
+10
Jun 17 '16 at 19:52
source share

there is already a team for this.

Copy one collection from one server to another. http://www.mongodb.org/display/DOCS/cloneCollection+Command

+2
May 30 '12 at 1:26
source share

If you are concerned about speed, I found that using aggregate with $project and $out will be 100 times faster, but not sure if there are any limitations, but you will need to create a set of fields that you want to copy For example:

// Set of fields in the categories collection var setOfFields = {field1:1, field2:1.......} db.demo1.categories.aggregate([{ "$project": setOfFields},{ $out: "demo2.categories"}]);

This copies (projects) the selected set of fields for all documents from demo1.categories to demo2.categories

+1
Jul 02 '15 at 18:13
source share

In the mongo console, you can also do the following: db_host is the machine on which db_host has db with the collection you want to clone.

using db.cloneCollection (,)

-2
Aug 09 '12 at 15:33
source share



All Articles