What's the fastest way to copy a collection wi

2019-01-08 07:58发布

问题:

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.

回答1:

You have a few options, but the fastest is:

mongodump -d db -c sourcecollection 
mongorestore -d db -c targetcollection --dir=dump/<db>/<sourcecollection.bson>

mongoexport -d db -c sourcecollection | mongoimport -d db -c targetcollection --drop

or in php:

`mongoexport -d db -c sourcecollection | mongoimport -d db -c targetcollection --drop`;

after that you have

mongo db < script.js

where, as shown in the mongo docs, script.js contains something like:

db.myoriginal.find().forEach( function(x){db.mycopy.insert(x)} );

The slowest (by an order of magnitude or more) way to copy a collection will be to use the native php driver - simply because of moving information around. But you could issue the above mongo query if you absolutely want to avoid cli calls using the db execute function.



回答2:

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

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



回答3:

The most simple & efficient way is by using copyTo(), so you can use:

db.source.copyTo("target"); 

& if "target" doesn't exist, it will be created

-- Update --

According to CopyTo Documentation, Because copyTo() uses eval internally, the copy operations will block all other operations on the mongod instance. So it shouldn't be used on production environment.

-- Update --

Because CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0.



回答4:

In addition to AD7six 1st solution, if you use mongoexport / import be sure about your collection data types and mongo configuration, as explained here: http://docs.mongodb.org/manual/reference/mongodb-extended-json/



回答5:

The fastest way is db.collection.copyTo().

Note that it is deprecated since version 3.0.



回答6:

You can use the copyDatabase function in the mongo shell:

http://docs.mongodb.org/manual/tutorial/copy-databases-between-instances/



标签: mongodb