Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

On the command line, this works:

$ mongo
> show dbs
mydatabase   1.0GB

However, this does not:

$ python    
>>> import pymongo
>>> connection = pymongo.MongoClient()
>>> connection.mydatabase.find()

I read through docs here:

http://api.mongodb.org/python/current/tutorial.html

But do not understand how to either...

  1. connect to an existing database (using pymongo)
  2. query what databases exist in the mongodb connection.

Why can't I access my database?

like image 625
Mittenchops Avatar asked Jan 22 '13 22:01

Mittenchops


People also ask

How do I get all the documents in a collection Pymongo?

To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.

How do I connect to Pymongo?

The first step to connect python to Atlas is MongoDB cluster setup. Next, create a file named pymongo_test_insert.py in any folder to write pymongo code. You can use any simple text editor like Textpad/Notepad. Use the connection_string to create the mongoclient and get the MongoDB database connection.


2 Answers

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/')

like image 88
The Red Pea Avatar answered Sep 20 '22 11:09

The Red Pea


Connect to an existing database

import pymongo
from pymongo import MongoClient
connection = MongoClient()
db = connection.mydatabase

List existing databases

import pymongo
from pymongo import MongoClient
connection = MongoClient()
# connection.database_names() # depreciated
connection.list_database_names()
like image 34
Talvalin Avatar answered Sep 21 '22 11:09

Talvalin