-
Type: Improvement
-
Resolution: Done
-
Priority: Minor - P4
-
Affects Version/s: None
-
Component/s: None
-
None
Background
--------------------
The MongoDB URI supports passing a database name to simplify initial authentication. It is intended to be used like this:
client = MongoClient("mongodb://user:pass@my.hostname.com:27017/my_db") db = client['my_db'] db.my_collection.find()
In the above example "client" is an instance of MongoClient, not an instance of Database. Since we passed the database name and credentials in the URI we don't have to do db.authenticate("user", "pass") before calling find().
What users expect is that, by passing a database name in the URI, they will immediately get a Database instance for the database name passed, regardless of whether or not authentication is enabled in MongoDB or them passing credentials in the URI.
Options
--------------------
There are a few ways this could be implemented. The first would be a function importable from pymongo:
from pymongo import database_from_uri db = database_from_uri("mongodb://my.hostname.com:27017/my_db")
Another is to provide a class method on MongoClient/MongoReplicaSetClient:
from pymongo import MongoClient db = MongoClient.database_from_uri("mongodb://my.hostname.com:27017/my_db")
However, returning a Database instance from a MongoClient class method feels like an abuse of class methods to me. Feel free to tell me I'm wrong.
Another option is to provide a class method on the Database class:
from pymongo.database import Database db = Database.from_uri("mongodb://my.hostname.com:27017/my_db")
Unfortunately this third option will likely require a bit of ugly code to avoid circular imports.
One more option:
import pymongo # MongoClient stores the database name from the uri as its "default" db client = pymongo.MongoClient(<uri with a database name>) # MongoClient returns a Database instance using the "default" database name db = client.get_default_database()
If option 1 and/or 3 are chosen, passing replicaSet=<replica set name> in the URI would cause the API to return an instance of Database created by an instance of MongoReplicaSetClient instead of MongoClient.
Please make suggestions in comments below.
- is duplicated by
-
PYTHON-634 Driver should not warn about "database name ignored"
- Closed
- related to
-
CDRIVER-632 Add mongoc_client_get_default_database
- Closed