69

I'm using pymongo and I can't figure out how to execute the mongodb interactive shell equivalent of "show dbs".

jacobra
  • 2,102
  • 2
  • 14
  • 20

3 Answers3

111
from pymongo import MongoClient
# Assuming youre running mongod on 'localhost' with port 27017
c = MongoClient('localhost',27017)
c.database_names()

Update 2020:

DeprecationWarning: database_names is deprecated

Use the following:

c.list_database_names()
Jeril
  • 7,858
  • 3
  • 52
  • 69
jacobra
  • 2,102
  • 2
  • 14
  • 20
  • 4
    Updating Answer as Connection()is now deprecated: http://api.mongodb.org/python/current/api/pymongo/connection.html – KLDavenport Jan 25 '14 at 01:02
  • 7
    `database_names` is now deprecated, we should use `list_database_names` instead. `for current_database in cliente.list_database_names():` – Renato Medeiros Sep 18 '19 at 13:50
13

as today it's

from pymongo import MongoClient
# client = MongoClient('host', port_number)
client = MongoClient('localhost', 27017)
cursor = client.list_databases()
for db in cursor:
    print(db)

or

from pymongo import MongoClient
# client = MongoClient('host', port_number)
client = MongoClient('localhost', 27017)
for db in client.list_databases():
    print(db)

If you use database_names, you will get "DeprecationWarning: database_names is deprecated. Use list_database_names instead."

Community
  • 1
  • 1
Shailyn Ortiz
  • 766
  • 4
  • 14
5

With Python3.5, you can try this way

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
print(client.list_database_names())