Quickstart: Get started using Azure Cosmos DB API for MongoDB and Python

APPLIES TO: Azure Cosmos DB API for MongoDB

This quickstart demonstrates how to:

  1. Create an Azure Cosmos DB API for MongoDB account
  2. Connect to your account using PyMongo
  3. Create a sample database and collection
  4. Perform CRUD operations in the sample collection

Prerequisites to run the sample app

  • Python 3.9+ (It's best to run the sample code described in this article with this recommended version. Although it may work on older versions of Python 3.)
  • PyMongo installed on your machine

Create a database account

  1. In a new browser window, sign in to the Azure portal.

  2. In the left menu, select Create a resource.

    Screenshot of creating a resource in the Azure portal.

  3. On the New page, select Databases > Azure Cosmos DB.

    Screenshot of the Azure portal Databases pane.

  4. On the Select API option page, select Azure Cosmos DB API for MongoDB > Create.

    The API determines the type of account to create. Select Azure Cosmos DB API for MongoDB because you will create a collection that works with MongoDB in this quickstart. To learn more, see Overview of Azure Cosmos DB API for MongoDB.

    Screenshot of the Select API option pane.

  5. On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Your account URI will be mongo.cosmos.azure.com appended to your unique account name.

    The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 44 characters long.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.

    Note: Only MongoDB API versions 4.2, 4.0, and 3.6 are supported by serverless accounts. Choosing 3.2 as the version will force the account in provisioned throughput mode.
    Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier.
    Version Choose the required server version Azure Cosmos DB API for MongoDB is compatible with the server version 4.2, 4.0, 3.6, and 3.2. You can upgrade or downgrade an account after it is created.


    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Screenshot of the new account page for Azure Cosmos DB.

  6. In the Global Distribution tab, configure the following details. You can leave the default values for the purpose of this quickstart:

    Setting Value Description
    Geo-Redundancy Disable Enable or disable global distribution on your account by pairing your region with a pair region. You can add more regions to your account later.
    Multi-region Writes Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across the globe.


    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes
  7. Optionally you can configure additional details in the following tabs:

    • Networking - Configure access from a virtual network.
    • Backup Policy - Configure either periodic or continuous backup policy.
    • Encryption - Use either service-managed key or a customer-managed key.
    • Tags - Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
  8. Select Review + create.

  9. The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Azure Cosmos DB API for MongoDB account is ready page.

    Screenshot of the Azure portal Notifications pane.

Learn the object model

Before you continue building the application, let's look into the hierarchy of resources in the API for MongoDB and the object model that's used to create and access these resources. The API for MongoDB creates resources in the following order:

  • Azure Cosmos DB API for MongoDB account
  • Databases
  • Collections
  • Documents

To learn more about the hierarchy of entities, see the Azure Cosmos DB resource model article.

Get the code

Download the sample Python code from the repository or use git clone:

git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started

Retrieve your connection string

When running the sample code, you have to enter your API for MongoDB account's connection string. Use the following steps to find it:

  1. In the Azure portal, select your Cosmos DB account.

  2. In the left navigation select Connection String, and then select Read-write Keys. You'll use the copy buttons on the right side of the screen to copy the primary connection string.


Never check passwords or other sensitive data into source code.

Run the code

python run.py

Understand how it works


The following code prompts the user for the connection string. It's never a good idea to have your connection string in code since it enables anyone with it to read or write to your database.

CONNECTION_STRING = getpass.getpass(prompt='Enter your primary connection string: ') # Prompts user for connection string

The following code creates a client connection your API for MongoDB and tests to make sure it's valid.

client = pymongo.MongoClient(CONNECTION_STRING)
    client.server_info() # validate connection string
except pymongo.errors.ServerSelectionTimeoutError:
    raise TimeoutError("Invalid API for MongoDB connection string or timed out when attempting to connect")

Resource creation

The following code creates the sample database and collection that will be used to perform CRUD operations. When creating resources programmatically, it's recommended to use the API for MongoDB extension commands (as shown here) because these commands have the ability to set the resource throughput (RU/s) and configure sharding.

Implicitly creating resources will work but will default to recommended values for throughput and will not be sharded.

# Database with 400 RU throughput that can be shared across the DB's collections
db.command({'customAction': "CreateDatabase", 'offerThroughput': 400})
 # Creates a unsharded collection that uses the DBs shared throughput
db.command({'customAction': "CreateCollection", 'collection': UNSHARDED_COLLECTION_NAME})

Writing a document

The following inserts a sample document we will continue to use throughout the sample. We get its unique _id field value so that we can query it in subsequent operations.

"""Insert a sample document and return the contents of its _id field"""
document_id = collection.insert_one({SAMPLE_FIELD_NAME: randint(50, 500)}).inserted_id

Reading/Updating a document

The following queries, updates, and again queries for the document that we previously inserted.

print("Found a document with _id {}: {}".format(document_id, collection.find_one({"_id": document_id})))

collection.update_one({"_id": document_id}, {"$set":{SAMPLE_FIELD_NAME: "Updated!"}})
print("Updated document with _id {}: {}".format(document_id, collection.find_one({"_id": document_id})))

Deleting a document

Lastly, we delete the document we created from the collection.

"""Delete the document containing document_id from the collection"""
collection.delete_one({"_id": document_id})

Next steps

In this quickstart, you've learned how to create an API for MongoDB account, create a database and a collection with code, and perform CRUD operations.

Trying to do capacity planning for a migration to Azure Cosmos DB? You can use information about your existing database cluster for capacity planning.