I want ti copy my collection including is indexes without the data. how can I do it in the most efficient way? I am using a replica set version 4.0.3


This can be done using the mongodump and mongorestore command line tools.

First, export the collection using mongodump. The export creates a BSON dump file with collection data and its indexes. You specify a query option for filtering the documents. In this case, the query filter will select zero documents. Effectively, this exports the indexes of the collection. For example,

> mongodump  --db=testdb --collection=srceColl  --query="{\"xyz\": \"one\"}"

Note the --query option has a JSON as a query, and the srceColl actually doesn't have a field named as xyz (you can specify any non-existing field, so that the query selects no documents). Also, the query requires the quotes and the inner quotes are escaped. The above command worked fine from Windows command prompt. Also, the connection string uri and any required options need to be specified for both the export and import commands.

The command creates a dump of the collection and its indexes in a folder called as dump\testdb\srceColl.BSON within the current folder.

Import into the target collection; you must specify the path to the dump BSON file.

> mongorestore --db=testdb --collection=trgtColl dump/test/srceColl.BSON

The newly created trgtCollcollection will have no data (zero documents) and the indexes will be same as that of the srceColl collection.

NOTE: This tested fine with MongoDB version 4.2.


Another way would be to use the copyTo() function.

NOTE: That will only work for MongoDB 4.0 and earlier.
Starting 4.2 it'll be deprecated. The dump/restore way is the proper way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.