Azure Cosmos DB JavaScript SDK
Overview
The Azure Cosmos DB JavaScript SDK provides a modern, async-oriented API for interacting with Azure Cosmos DB using Node.js or browser environments. It supports SQL (Core) API, MongoDB API, Cassandra API, Gremlin API, and Table API through a unified client.
Installation
Install the package from npm:
npm install @azure/cosmos
For TypeScript projects, the types are included out of the box.
Quick Start
Create a database, a container, and insert a document:
const { CosmosClient } = require("@azure/cosmos");
const endpoint = "https://<your-account>.documents.azure.com:443/";
const key = "<your-key>";
const client = new CosmosClient({ endpoint, key });
async function run() {
const { database } = await client.databases.createIfNotExists({ id: "SampleDB" });
const { container } = await database.containers.createIfNotExists({ id: "Items" });
const item = { id: "item1", name: "Azure SDK", category: "Documentation" };
await container.items.create(item);
console.log("Item created");
}
run().catch(console.error);
CRUD Operations
Create
await container.items.create({ id: "newItem", description: "New item" });
Read
const { resource } = await container.item("newItem").read();
console.log(resource);
Update
const { resource: updated } = await container
.item("newItem")
.replace({ id: "newItem", description: "Updated description" });
Delete
await container.item("newItem").delete();
Query API
Use SQL syntax to query items. The SDK returns an iterator that can be read page by page.
const querySpec = {
query: "SELECT * FROM c WHERE c.category = @category",
parameters: [{ name: "@category", value: "Documentation" }]
};
const { resources } = await container.items.query(querySpec).fetchAll();
console.log(resources);
Partitions
Define a partition key when creating a container. Example uses /category as the partition key.
await database.containers.createIfNotExists({
id: "Items",
partitionKey: { paths: ["/category"], version: 2 }
});
When reading or writing items, include the partition key value to improve performance.
Best Practices
- Leverage bulk execution for high-throughput workloads.
- Use
createIfNotExiststo make provisioning idempotent. - Employ retry policies provided by the SDK for transient faults.
- Prefer queries that include the partition key to avoid cross‑partition scans.
API Reference
Key classes:
CosmosClient– Entry point for all operations.Database– Manage databases.Container– Manage containers and items.Item– CRUD on individual documents.BulkOperations– Perform bulk inserts/updates.
Full API documentation is available on the official Azure docs site.