pymongo default database connection

mongodb, pymongo, python

Solution

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

Problem

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?

Original source