How do I use pymongo to connect to an existing document collection/db? How do I use pymongo to connect to an existing document collection/db? mongodb mongodb

How do I use pymongo to connect to an existing document collection/db?


Connect to an existing database

import pymongofrom pymongo import MongoClientconnection = MongoClient()db = connection.mydatabase

List existing databases

import pymongofrom pymongo import MongoClientconnection = MongoClient()# connection.database_names() # depreciatedconnection.list_database_names()


The question implies user has a local MongoDB. However I found this question trying to connect to a remote MongoDB. I think the tutorial is worth mentioning (no other answer here mentioned how I can specify the host and the port)

The above code will connect on the default host and port. We can also specify the host and port explicitly, as follows:

client = MongoClient('localhost', 27017)

Or use the MongoDB URI format:

client = MongoClient('mongodb://localhost:27017/')


show dbs and find() are totally different commands as such you cannot compare the two.

connection.mydatabase.find()

Will actually do nothing because you cannot find() documents on database level. You are probably looking for:

cursor = connection.mydatabase.mycol.find()

I am no Python programmer but something like that and the foreach the cursor var to get your data.

As an added note you will want to replace mycol with the collection name that contains your documents.

As for querying for a list of databases you can do something like:

databases = connection.mydatabase.command({'listDatabases': 1});

As shown here: http://docs.mongodb.org/manual/reference/command/listDatabases/#listDatabases

However again I am no Python programmer but this should get you started.