2

I need to rename a database I created using pymongo. I'd like to use pymongo to do it. I found this other stackoverflow question that is very similar, and the code snippets look pythonesque, except the use keyword which makes it... I don't know what (Update: Perl probably?).

I did a

client.copy_database('old_name', 'new_name)

And found that I then had new_name in `client.database_names()'. But it appears to have no collections in it? What else do I need to do, to deeply copy the database, using pymongo commands?

Community
  • 1
  • 1
Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • copy_database is the right way to do it. Are you sure that command was successful and you copied right database? – zero323 Sep 05 '13 at 22:01

3 Answers3

4

From PyMongo 3.0 onwards, you have to use admin.command since copy_database was removed in 3.0:

client.admin.command('copydb',
                     fromdb='source_db_name',
                     todb='target_db_name')
user2804197
  • 354
  • 5
  • 13
1
import pymongo
client = pymongo.MongoClient()

client.copy_database('foo', 'bar')

assert set(client['foo'].collection_names()) == set(client['bar'].collection_names())

for collection in client['foo'].collection_names():
    assert client['foo'][collection].count() == client['bar'][collection].count()

client.drop_database('foo')
zero323
  • 322,348
  • 103
  • 959
  • 935
  • I tried this. It even answered True. But when I do `for e in client.old_name.twigs.find(): print(e)`, I see a bunch of things. But when I do `for e in client.new_name.twigs.find(): print(e)`, it prints nothing. Which makes me think it didn't really deep copy? – Travis Griggs Sep 05 '13 at 22:15
  • I can't spell my own database names. Sigh. Dang. Sorry. (Interpret, it _did_ work) – Travis Griggs Sep 05 '13 at 22:21
0

I tried all above ways but none worked for me, The script below has worked for me and thought it would work for you as well.(Note: con is my database connection )

def rename_database(old_name,new_name):
        #copying collections and documents from old to new database
        for i in con[old_name].list_collection_names():
            con[new_name][i]
            for j in con[old_name][i].find():
                a=con[new_name][i].insert_one(j)
        #dropping old database
        con.drop_database(old_name)

#testing purpose
rename_database("test","newDbName")