Manage a MongoDB database using Python

APPLIES TO: MongoDB

Your MongoDB server in Azure Cosmos DB is available from the common Python packages for MongoDB such as:

  • PyMongo for synchronous Python applications and used in this article.
  • Motor for asynchronous Python applications.

Note

The example code snippets are available on GitHub as a Python project.

Name a database

In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.

Here are some quick rules when naming a database:

Once created, the URI for a database is in this format:

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>

Get database instance

The database holds the collections and their documents. To access a database, use attribute style access or dictionary style access of the MongoClient. For more information, see Getting a Database.

The following code snippets assume you've already created your client connection and that you close your client connection after these code snippets.

Get server information

Access server info with the server_info method of the MongoClient class. You don't need to specify the database name to get this information. The information returned is specific to MongoDB and doesn't represent the Azure Cosmos DB platform itself.

You can also list databases using the MongoClient.list_database_names method and issue a MongoDB command to a database with the MongoClient.db.command method.

# Get server information
for k, v in client.server_info().items():
    print("Key: {} , Value: {}".format(k, v))

# Get server status of admin database
print("Server status {}".format(client.admin.command("serverStatus")))

# List databases
databases = client.list_database_names()
print("Databases: {}".format(databases))

The preceding code snippet displays output similar to the following example console output:

Key: version , Value: 3.6.0
Key: versionArray , Value: [3, 6, 0, 0]
Key: bits , Value: 64
Key: maxBsonObjectSize , Value: 16777216
Key: ok , Value: 1.0
Server status {'ok': 1.0}
Databases: ['adventureworks']

Does database exist?

The PyMongo driver for Python creates a database if it doesn't exist when you access it. However, we recommend that instead you use the MongoDB extension commands to manage data stored in Azure Cosmos DB’s API for MongoDB. To create a new database if it doesn't exist, use the create database extension as shown in the following code snippet.

To see if the database already exists before using it, get the list of current databases with the list_database_names method.

# Get list of databases
databases = client.list_database_names()
if not databases:
    print("No databases found")

# Does database exist?
DB_NAME = "adventureworks"
if DB_NAME in databases:
    print("Database exists: {}".format(DB_NAME))
else:
    client[DB_NAME].command(
        {"customAction": "CreateDatabase", "offerThroughput": 400}
    )
    print("Created db '{}' with shared throughput.\n".format(DB_NAME))

The preceding code snippet displays output similar to the following example console output:

Database exists: adventureworks

Get list of databases, collections, and document count

When you manage your MongoDB server programmatically, it's helpful to know what databases and collections are on the server and how many documents in each collection. For more information, see:

# Get list of databases
databases = client.list_database_names()

# Loop through databases
for db in databases:
    print("Database: {}".format(db))

    # Get list of collections
    collections = client[db].list_collection_names()

    # Loop through collections
    for col in collections:
        print("\tCollection: {}".format(col))

        # Get document count
        doc_count = client[db][col].count_documents({})
        print("\tDocument count: {}".format(doc_count))

The preceding code snippet displays output similar to the following example console output:

Database: adventureworks
        Collection: products_new
        Document count: 1
        Collection: products
        Document count: 3
Database: testdb
        Collection: mycoll
        Document count: 1

Get database object instance

If a database doesn't exist, the PyMongo driver for Python creates it when you access it. However, we recommend that instead you use the MongoDB extension commands to manage data stored in Azure Cosmos DB’s API for MongoDB. The pattern is shown above in the section Does database exist?.

When working with PyMongo, you access databases using attribute style access on MongoClient instances. Once you have a database instance, you can use database level operations as shown below.

collections = client[db].list_collection_names()

For an overview of working with databases using the PyMongo driver, see Database level operations.

Drop a database

A database is removed from the server using the drop_database method of the MongoClient.

DB_NAME = input("Enter database name to drop: ")
if DB_NAME in client.list_database_names():
    print("Dropping database: {}".format(DB_NAME))
    client.drop_database(DB_NAME)
else:
    print("Didn't find database: {}".format(DB_NAME))

The preceding code snippet displays output similar to the following example console output:

Enter database name to drop: adventureworks
Dropping database: adventureworks

See also