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.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; } // POST: api/student [HttpPost] public async Task<IActionResult> AddStudent(Student student) { await _service.AddStudentAsync(student); return Ok("Student Added"); } // GET: api/student/{id}/{city} [HttpGet("{id}/{city}")] public async Task<IActionResult> GetStudent( string id, string city) { var student = await _service.GetStudentAsync(id, city); if(student == null) return NotFound("Student not found"); return Ok(student); } // GET: api/student // Get All Students [HttpGet] public async Task<IActionResult> GetAllStudents() { var students = await _service.GetAllStudentsAsync(); return Ok(students); } // PUT: api/student // Update Student [HttpPut] public async Task<IActionResult> UpdateStudent( Student student) { var result = await _service.UpdateStudentAsync(student); if(result == null) return NotFound("Student not found"); return Ok("Student Updated"); } // DELETE: api/student/{id}/{city} // Delete Student [HttpDelete("{id}/{city}")] public async Task<IActionResult> DeleteStudent( string id, string city) { var result = await _service.DeleteStudentAsync( id, city); if(!result) return NotFound("Student not found"); return Ok("Student Deleted"); } } }
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.

0 Comments
POST Answer of Questions and ASK to Doubt