What is Azure Cosmos DB?
Azure Cosmos DB is a fully managed NoSQL database service provided by Microsoft Azure.
Key Features
- Globally distributed database
- High performance and low latency
- Automatic scaling
- NoSQL document database
- Supports JSON data
- Multi-region replication
- High availability (99.999%)
Example Document
Unlike SQL Server tables, Cosmos DB stores data as JSON documents.
{
"id": "1",
"name": "Shiva Gautam",
"email": "shiva@gmail.com",
"city": "Bhopal"
}
Cosmos DB Terminology
| SQL Server | Cosmos DB |
|---|---|
| Database | Database |
| Table | Container |
| Row | Document |
| Column | Property |
| Primary Key | id |
Step 1: Create Azure Cosmos DB Account
Login to Azure Portal
- Click Create a Resource
- Search:
Azure Cosmos DB
- Select:
Azure Cosmos DB for NoSQL
- Click Create
Fill Details
Resource Group
CosmosDB-RG
Account Name
shivacosmosdb
Region
Central India
Capacity Mode
Serverless
(Serverless is best for learning)
Click:
Review + Create
Then:
Create
Deployment may take 2-5 minutes.
Step 2: Create Database
After deployment:
Cosmos DB Account
→ Data Explorer
→ New Database
Database Name:
StudentDB
Click OK.
Step 3: Create Container (Table)
In Cosmos DB, Table = Container.
Create Container
Database : StudentDB
Container : Students
Partition Key : /city
Click OK.
Step 4: Insert Sample Data
Open:
Students
→ Items
→ New Item
Paste:
{
"id": "1",
"name": "Shiva Gautam",
"email": "shiva@gmail.com",
"city": "Bhopal"
}
Click Save.
Step 5: Create .NET Core Web API Project
Open Visual Studio
Create New Project
Select:
ASP.NET Core Web API
Project Name:
CosmosDemoAPI
Framework:
.NET 8
Create.
Step 6: Install NuGet Package
Open Package Manager Console
Install-Package Microsoft.Azure.Cosmos
Or
dotnet add package Microsoft.Azure.Cosmos
Step 7: Get Connection Information
Azure Portal
Cosmos DB
→ Keys
Copy:
URI
Primary Key
Example:
https://shivacosmosdb.documents.azure.com:443/
XXXXXXXXXXXXXXXXXXXX
Step 8: Configure appsettings.json
{
"CosmosDb": {
"Account": "https://shivacosmosdb.documents.azure.com:443/",
"Key": "YOUR_PRIMARY_KEY",
"DatabaseName": "StudentDB",
"ContainerName": "Students"
}
}
Step 9: Create Model
Models/Student.cs
namespace CosmosDemoAPI.Models
{
public class Student
{
public string id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string City { get; set; }
}
}
Step 10: Create Cosmos Service
Services/CosmosDbService.cs
using Microsoft.Azure.Cosmos;
using CosmosDemoAPI.Models;
namespace CosmosDemoAPI.Services
{
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(IConfiguration configuration)
{
CosmosClient client = new CosmosClient(
configuration["CosmosDb:Account"],
configuration["CosmosDb:Key"]);
Database database =
client.GetDatabase(
configuration["CosmosDb:DatabaseName"]);
_container =
database.GetContainer(
configuration["CosmosDb:ContainerName"]);
}
public async Task AddStudentAsync(Student student)
{
await _container.CreateItemAsync(
student,
new PartitionKey(student.City));
}
public async Task<Student> GetStudentAsync(string id, string city)
{
ItemResponse<Student> response =
await _container.ReadItemAsync<Student>(
id,
new PartitionKey(city));
return response.Resource;
}
}
}
Step 11: Register Service
Program.cs
builder.Services.AddSingleton<CosmosDbService>();
Step 12: Create Controller
Controllers/StudentController.cs
using Microsoft.AspNetCore.Mvc;
using CosmosDemoAPI.Models;
using CosmosDemoAPI.Services;
namespace CosmosDemoAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class StudentController : ControllerBase
{
private readonly CosmosDbService _service;
public StudentController(
CosmosDbService service)
{
_service = service;
}
[HttpPost]
public async Task<IActionResult> AddStudent(
Student student)
{
await _service.AddStudentAsync(student);
return Ok("Student Added");
}
[HttpGet("{id}/{city}")]
public async Task<IActionResult> GetStudent(
string id,
string city)
{
var student =
await _service.GetStudentAsync(
id,
city);
return Ok(student);
}
}
}
Step 13: Run Application
Swagger Opens
POST
POST /api/student
Request Body
{
"id":"2",
"name":"Amit",
"email":"amit@gmail.com",
"city":"Indore"
}
GET
GET /api/student/2/Indore
Output
{
"id": "2",
"name": "Amit",
"email": "amit@gmail.com",
"city": "Indore"
}
CRUD Operations
Insert
CreateItemAsync()
Read
ReadItemAsync()
Update
ReplaceItemAsync()
Delete
DeleteItemAsync()
Query
GetItemQueryIterator<T>()
Example:
var query = new QueryDefinition(
"SELECT * FROM c WHERE c.city='Bhopal'");
SQL Server vs Cosmos DB
| Feature | SQL Server | Cosmos DB |
|---|---|---|
| Type | Relational | NoSQL |
| Schema | Fixed | Flexible |
| Scale | Manual | Automatic |
| Global Distribution | Limited | Built-in |
| Data Format | Rows | JSON Documents |
| Joins | Yes | Limited |
| Performance | Good | Extremely Fast |
When to Use Cosmos DB?
✅ E-Commerce Applications
✅ Social Media Applications
✅ IoT Applications
✅ Chat Applications
✅ Real-Time Analytics
✅ Global Applications
Avoid Cosmos DB if:
- Complex SQL joins are required.
- Traditional relational databases fit better.
- Strong relational constraints are essential.
For teaching students, a good next step is to build a complete CRUD Web API with Cosmos DB and then connect it to an ASP.NET Core MVC or React frontend.
0 Comments
POST Answer of Questions and ASK to Doubt