17

I need to connect to MongoDB from my Python code, the only thing I have is a url. Per mongo URL doc I can specify database name:

mongodb://host/db_name

Now I would like to use exactly database specified from URL and don't want to parse it manually to extract name of database. But MongoClient have no interface to access default one. Any thoughts how to manage this?

4 Answers 4

30

PyMongo/MongoClient provides a get_default_database() method:

from pymongo import MongoClient

client = MongoClient("mongodb://host/db_name")
db = client.get_default_database()

https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html

Sign up to request clarification or add additional context in comments.

2 Comments

get_default_database() is deprecated(), use get_database() instead
get_default_database() has been undeprecated since 3.8 pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html Changed in version 3.8: Undeprecated. Added the default, codec_options, read_preference, write_concern and read_concern parameters.
3

You can use pymongo.uri_parser.parse_uri for this:

Python 2.7.5 (default, Jul 12 2013, 14:44:36) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> uri = "mongodb://user:[email protected]/my_database/?w=2"
>>> from pymongo.uri_parser import parse_uri
>>> parse_uri(uri)
{'username': 'user', 'nodelist': [('example.com', 27017)], 'database': 'my_database/',
'collection': None, 'password': 'pass', 'options': {'w': 2}}

In PyMongo 2.6 there will be a get_default_database() method for this. See PYTHON-461

Comments

2

I got this error from Dan's answer:

OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

Solution

I realized I needed to specify the authentication source as there is authentication to my instance. If you face the same, use this:

from pymongo import MongoClient

client = MongoClient("mongodb://<USERNAME>:<PASSWORD>@<HOST>/<DEFAULT_DATABASE>?authSource=admin")
db = client.get_default_database()

# Then you may query
db["my_col"].find_one({})

Fill <USERNAME>, <PASSWORD>, <HOST>, <DEFAULT_DATABASE> accordingly (read more about MongoDB connection strings).

You may have the authSource in another database but I think admin is the default.

Comments

0

Looks like it doesn't work at all. When starting pymongo dumps warning:

UserWarning: database name or authSource in URI is being ignored.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.