Copying a Database

To copy a database within a single mongod process, or between mongodservers, simply connect to the target mongod and use thecommand() method:

  1. >>> from pymongo import MongoClient
  2. >>> client = MongoClient('target.example.com')
  3. >>> client.admin.command('copydb',
  4. fromdb='source_db_name',
  5. todb='target_db_name')

To copy from a different mongod server that is not password-protected:

  1. >>> client.admin.command('copydb',
  2. fromdb='source_db_name',
  3. todb='target_db_name',
  4. fromhost='source.example.com')

If the target server is password-protected, authenticate to the “admin”database:

  1. >>> client = MongoClient('target.example.com',
  2. ... username='administrator',
  3. ... password='pwd')
  4. >>> client.admin.command('copydb',
  5. fromdb='source_db_name',
  6. todb='target_db_name',
  7. fromhost='source.example.com')

See the authentication examples.

If the source server is password-protected, use the copyDatabasefunction in the mongo shell.

Versions of PyMongo before 3.0 included a copy_database helper method,but it has been removed.