Azure Cosmos DB is a **fully managed NoSQL database** service by Microsoft. It is designed for **global distribution, high availability, and low-latency performance**.
Azure Cosmos DB - Complete Guide
What is Azure Cosmos DB?
Azure Cosmos DB is a **fully managed NoSQL database** service by Microsoft. It is designed for **global distribution, high availability, and low-latency performance**.
Key Features of Cosmos DB
- Multi-Model Support: Supports document, key-value, column-family, and graph databases.
- Global Distribution: Data is replicated automatically across multiple regions.
- Guaranteed Latency: Less than **10ms** read and write latency.
- Five Consistency Levels: Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual.
- Automatic Scaling: Adjusts throughput dynamically.
Creating an Azure Cosmos DB Account
Step 1: Create a Cosmos DB Account
az cosmosdb create --name my-cosmosdb --resource-group MyResourceGroup --kind MongoDB
Step 2: Create a Database
az cosmosdb database create --name mydatabase --resource-group MyResourceGroup --account-name my-cosmosdb
Step 3: Create a Collection
az cosmosdb collection create --name mycollection --resource-group MyResourceGroup --account-name my-cosmosdb --database-name mydatabase
Connecting to Cosmos DB
Using Python (MongoDB API)
from pymongo import MongoClient
cosmos_url = "mongodb://my-cosmosdb.documents.azure.com:10255/?ssl=true"
client = MongoClient(cosmos_url, username="myuser", password="mypassword")
db = client["mydatabase"]
collection = db["mycollection"]
# Insert a document
collection.insert_one({"name": "Azure Cosmos DB", "type": "NoSQL"})
# Fetch documents
for doc in collection.find():
print(doc)
Using Node.js
const { CosmosClient } = require("@azure/cosmos");
const endpoint = "https://my-cosmosdb.documents.azure.com";
const key = "your-primary-key";
const client = new CosmosClient({ endpoint, key });
const database = client.database("mydatabase");
const container = database.container("mycollection");
// Insert a document
async function addItem() {
await container.items.create({ id: "1", name: "Azure Cosmos DB", type: "NoSQL" });
}
addItem();
Scaling Azure Cosmos DB
Manual Scaling
az cosmosdb update --name my-cosmosdb --resource-group MyResourceGroup --throughput 10000
Auto Scaling
az cosmosdb update --name my-cosmosdb --resource-group MyResourceGroup --max-throughput 50000
Global Replication
Azure Cosmos DB supports **multi-region replication**.
az cosmosdb update --name my-cosmosdb --resource-group MyResourceGroup --locations eastus westus
Monitoring and Performance
Check Throughput Usage
az monitor metrics list --resource MyResourceGroup --name my-cosmosdb --metric "TotalRequestUnits"
Conclusion
Azure Cosmos DB is an **enterprise-grade NoSQL database** with **global distribution, low-latency, and scalability**.
📌 Next Topic: Azure DevOps - CI/CD and Pipelines