How to Run MongoDB Queries on Azure Cosmos DB Using Python

Azure Cosmos DB is a highly scalable and fully managed database service available on the Azure cloud platform. Using MongoDB API support, it is possible to store JSON documents in Azure Cosmos DB. If you are using Cosmos DB with MongoDB API support in your projects, sometimes you need quick Python scripts to analyse data. Python can be used to quickly run queries on Cosmos DB. If you are using python to connect to production database, use only the read-only access keys for the Cosmos DB. Read-only keys are available on a separate tab in the Azure portal page for Cosmos DB (Azure Cosmos DB => Connection String => Read-only Keys).

The following sample python program uses pymongo package to connect to Cosmos DB. If you don’t have pymongo already installed, run the following command,

sudo pip3 install pymongo

The following python program connects to the Azure Cosmos DB and then prints documents in a collection. Don’t forget to replace the variables with the details of your database. Also note that the following program requires python 3.6 or above.

from pymongo import MongoClient
import json

# Get these values from the Azure portal page for your cosmos db account
cosmos_user_name = "cosmostestdbaccountname"
cosmos_password = "C7qC0lae6C6gNqRbiNYvhQgchsWWCLJpgLNA0hwA4IsJSLKDK=="
cosmos_url = ""
cosmos_database_name = "cosmostestdb"
cosmos_collection_name = "cosmostestcollection"

# This requires python 3.6 or above
uri = f'mongodb://{cosmos_user_name}:{cosmos_password}@{cosmos_url}'
mongo_client = MongoClient(uri)

# This is the name of the Mongo compatible database
my_db = mongo_client[cosmos_database_name]

# The name of the collection you are querying
my_col = my_db[cosmos_collection_name]
my_docs = my_col.find({})

# Prints all documents in the collection
for doc in my_docs:

Do you have a question on the above article or do you have a programming problem that you are unable to solve? Please email us.

Comments are closed.