Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-461

API to create a database.Database instance directly from a URI.

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 2.6
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      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.

            Assignee:
            jesse@mongodb.com A. Jesse Jiryu Davis
            Reporter:
            bernie@mongodb.com Bernie Hackett
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated:
              Resolved: